skip to Main Content

I’m currently developing a reservation system and the authentication I use is JWT and saving it in my cookie.This is how I send the cookie after the user login.

  • React Login
  const login = async () => {
    const requestOptions = {
      credentials: 'same-origin',
      withCredentials: true,
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      path: '/',
      body: JSON.stringify({
        id: "User ID",
        password: "Password"
      })
    };

    fetch('https://localhost:4000/auth/login', requestOptions)
      .then(res => res.json())
      .then(response => {
        console.log('result login', response)
      })
      .catch((e) => {
        console.log('[error] login', e)
      })
    // empty dependency array means this effect will only run once (like componentDidMount in classes)
  };
  useEffect(() => {
    login()
  }, []);

  • Nest JS
@Controller('auth')
export class AuthController {
  constructor(private authService: AuthService) {}

  @UseGuards(LocalGuard)
  @Post('login')
  async login(
    @Body() data: UserLoginDto,
    @Res({ passthrough: true }) res: Response,
  ) {
    console.log('[LOGIN]', data);
    const access_token = this.authService.login(data);

    res.cookie('access_token', access_token, {
      httpOnly: true,
      secure: true,
      sameSite: 'none',
      path: '/',
      maxAge: 10000,
      expires: new Date(Date.now() + 1 * 24 * 60 * 1000),
    });
    return access_token;
  }

then I can see a cookie data like this.

Cookie data

However, It isn’t stored in my browser.
enter image description here

I’d tried credentials, https, httpOnly, Secure, sameSite, expires options. But these didn’t working and still get in.
Is there way to store cookie? Please help me.

Fix and New Error

I stored my cookie! But I got Cors error. I think access-control-allow-origin: * is problem. Therefore, I fixed my code like this

  • Nest Js
  app.enableCors({
    origin: [
      'https://127.0.0.1:3000',
      'https://localhost:3000',
    ],
    credentials: true,
    // methods: ['GET', 'POST'],
    // allowedHeaders: ['Content-Type', 'Authorization'],
    // maxAge: 86400,
  });

but ‘access-control-allow-origin’ isn’t changed.
access-control-allow-origin: *

How can I fix access-control-allow-origin?

2

Answers


  1. I’m guessing this is your testing environment, so the React app is running on a different port than the Nest.js app, right?

    Your Nest app needs to allow the React app’s origin for CORS. Add this to your main.ts:

    app.enableCors({
       origin: [
          'http://localhost:3000',
       ],
       credentials: true,
    });
    

    Replace the port number with the port of your React app.

    Further reading on CORS, if you’re interested: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS

    Edit: After reading your cookie configuration again, it might also be an issue with those. It seems you’re running the app on localhost, but having secure set to true, which won’t work for a non-HTTPS environment. I’d suggest setting secure conditionally, depending on if the app is running locally or in production. Also the credentials: 'same-origin' configuration might not work for different ports.

    Login or Signup to reply.
  2. Why are you commenting out the methods allowed? To enable cors, you should specify the origins and the methods allowed. Uncomment the methods option and it should work:

    app.enableCors({
        origin: [
          'https://localhost:3000',
        ],
        credentials: true,
        // you can list out only the methods you are interested in
        methods: ['GET', 'HEAD', 'PUT', 'PATCH', 'POST', 'DELETE'];,
      });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search