Questions & Answers

Getting 401 Unauthorized when using browser

I am creating SPA with Nest.js and React.js and wanted to use passport JWT authentication but run into a problem. After successful login in browser, 401 Error occurs while trying to access routes protected by JwtAuthGuard, like adding new article or logging out. When trying to add new article or log out after successful login using Insomnia, everything works as intended. Why authentication only works when using Insomnia? Do I need to authorize React using cors and provide credentials?


import { ExtractJwt, Strategy } from "passport-jwt";
import { PassportStrategy } from "@nestjs/passport";
import { Injectable, UnauthorizedException } from "@nestjs/common";
import { UserEntity } from "src/user/entities/user.entity";

export interface JwtPayload {
  id: string;

function cookieExtractor(req: any): null | string {
  return (req && req.cookies) ? (req.cookies?.jwt ?? null) : null

export class JwtStrategy extends PassportStrategy(Strategy) {
  constructor() {
      jwtFromRequest: cookieExtractor,
      secretOrKey: process.env.SECRET_OR_KEY,

  async validate(payload: JwtPayload, done: (error: Error, user: UserEntity | boolean) => void) {
    if (!payload || ! {
      return done(new UnauthorizedException(), false);
    const user = await UserEntity.findOne({where: {
    if (!user) {
      return done(new UnauthorizedException(), false)
    done(null, user);

I've tried changing jwtFromRequest from cookieExtractor to ExtractJwt.fromAuthHeaderAsBearerToken(), but no results.

2023-01-07 20:29:40
Is the browser sending the cookie with the request? When you changed it to the header parsers did you send the jwt in the header as expected?
Answers(0) :