Search code examples
typescriptexpresscookiesjwtnestjs

How to set HTTP only cookie in NestJS


I am trying to implement JWT authorization with accessToken and refreshToken. Both the accessToken and refresh token need to be set in HTTP only cookie.

I tried this code but it is not setting cookies. I am using NestJS framework here.

import { Controller, Request, Post, Body, Response } from '@nestjs/common';
@Controller()
export class UserController {
  constructor() {}

  @Post('users/login')
  async login(
    @Request() req,
    @Body() credentials: { username: string; password: string },
    @Response() res,
  ) {
    try {
      // Login with username and password
      const accessToken = 'something';
      const refreshToken = 'something';
      const user = { username: credentials.username };

      res.cookie('accessToken', accessToken, {
        expires: new Date(new Date().getTime() + 30 * 1000),
        sameSite: 'strict',
        httpOnly: true,
      });
      return res.send(user);
    } catch (error) {
      throw error;
    }
  }
}

The res.send() method is working fine i am getting data in response .How can i set cookie here ?

This is my main.ts file: -

import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { Logger } from '@nestjs/common';
import { AuthenticatedSocketIoAdapter } from './chat/authchat.adapter';
import * as cookieParser from 'cookie-parser';
async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  app.enableCors();
  app.use(cookieParser());
  app.useWebSocketAdapter(new AuthenticatedSocketIoAdapter(app));
  await app.listen(3000);
  Logger.log('User microservice running');
}
bootstrap();

And to get the cookie I am using:-

request.cookies

Solution

  • Conversation in the comments:

    Axios, on the client side, needs to have withCredentials set to true to send the cookies back to the server. The server was sending and setting thecookies as expected.