Enabling cookie communication between NestJS server and Next.js frontend

I seem to be encountering challenges when trying to set cookies from a NestJS backend into my Next.js app.

My NestJS application is running on port 3001 and here is my bootstrap setup:

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  app.enableCors({
    origin: 'http://localhost:3000',
    credentials: true,
  });

  app.use(cookieParser());
  await app.listen(3001);
}
bootstrap();

To test it, I have created a GET endpoint:

@Get()
async getAll(@Req() request: Request, @Res() response: Response) {

  console.log(request.cookies);
  response.cookie('name', 'value', {
    httpOnly: true,
    secure: false,
    sameSite: 'none',
  });

  return response.send('ok');
}

In the Next.js file src/app/api/signin/route.ts, I have the following code:

'use server'

import { NextRequest, NextResponse } from "next/server";
import axios, { AxiosHeaderValue } from 'axios';
import { cookies } from "next/headers";

export async function POST(request: NextRequest, res: NextResponse) {

  const response = await axios.get("http://localhost:3001/test", {
    headers: {
      "Content-Type": "application/json"
    },
    withCredentials: true,
  });

  console.log(response.headers)

  return new NextResponse(JSON.stringify(response.data))
}

All seems well, as the console logs print the set-cookie:

Object [AxiosHeaders] {
  'x-powered-by': 'Express',
  'access-control-allow-origin': 'http://localhost:3000',
  vary: 'Origin',
  'access-control-allow-credentials': 'true',
  'set-cookie': [ 'name=value; Path=/; HttpOnly; SameSite=None' ],
  'content-type': 'text/html; charset=utf-8',
  'content-length': '2',
  etag: 'W/"2-eoX0dku9ba8cNUXvu/DyeabcC+s"',
  date: 'Tue, 19 Mar 2024 09:45:14 GMT',
  connection: 'keep-alive',
  'keep-alive': 'timeout=5'
}

However, if I call the same endpoint again, the console.log(request.cookies); in the backend returns null.

Shouldn't the set-cookie directive set the cookie in the backend? And with axios withCredentials, shouldn't it use them?

What am I missing? The Next.js tutorials are somewhat confusing, and despite trying for the past two days, I can't seem to successfully set the cookies on the request...

Answer №1

Secure cookies known as "httpOnly" are specifically designed to be out of reach for JavaScript code. These cookies can only be manipulated through the backend provided by nestjs.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Angular 7: An unexpected error occurred when trying to inject TripsMenu into MenuWidgetComponent in AppModule

Encountering an issue in angular 7, where I am trying to inject my MenuWidgetComponent in the home component. I have imported it in the widget component and exported it via index.ts. However, the following error persists: I searched online but couldn&apos ...

Encountering an undefined property error while using Array.filter in Angular 2

hello everyone, I am currently faced with an issue while working on a project that involves filtering JSON data. When using the developer tools in Chrome, it keeps showing me an error related to undefined property. chart: JsonChart[] = []; charts: JsonC ...

Having trouble with Next Auth getSession in api routes

When I utilize getServerSideProps to access APIs, calling getSession in the getServerSideProps() function returns a valid object. export async function getServerSideProps({ req }) { const session = await getSession({ req }); // works However, if I call ...

Creating a Session Timeout feature for Ionic/Angular that includes resetting the timer with each new user interaction

Having trouble implementing a session timeout feature in my code. I need the timer to reset whenever a user interacts with the function. Can't figure out how to integrate similar code like the one provided as an example on Stack Overflow. This is the ...

Transferring data from an Angular 2 component to a service

I am trying to pass data from an Angular component to a service and utilize the service's methods to manipulate it. Here is an example: class SomeComponent { public info: Array<any> = MyData; constructor(private myService: TablePag ...

Implementing typing for a module that exports an instance of a particular class

Attempting to create a .d.ts file for the foo-foo-mq module has presented some challenges. Following the documentation, a 'foo-foo-mq' folder was created within the 'typings' directory at the project's root. An index.d.ts file was ...

Incorporating lodash in a project with TypeScript and jspm

I seem to be missing something in my setup and would appreciate any assistance. I am working with TypeScript 2 + JSPM. I have tried various configurations in tsconfig using typeRoots and types (including adding the version number in the type name). Despite ...

Steps for integrating Cordova-vk plugin into an Ionic 3 project

I am looking to incorporate the cordova-vk plugin into my app, but I am having trouble connecting it to Typescript. vkSdk is not defined I understand that the plugin is located in the node_modules folder. How can I successfully integrate it into my page ...

Error in React Typescript: No suitable index signature with parameter type 'string' was located on the specified type

I have encountered an issue while trying to dynamically add and remove form fields, particularly in assigning a value for an object property. The error message I received is as follows: Element implicitly has an 'any' type because expression o ...

What is the procedure for including a js file in typescript?

I am trying to import a js file in typescript and access objects and functions within the file. I have added the js file in index.html, but it is not working as expected. I tried using "import '[js file path]'" but it did not work. import { Comp ...

Is it possible to integrate a personalized theme into react-dates?

Attempting to customize the styling of my react-dates DayPickerRangeController in Typescript using react-with-styles and Aphrodite. I have implemented the following code, mirroring the code found at https://github.com/airbnb/react-dates#interfaces: const ...

The type 'Function' does not contain any construct signatures.ts

Struggling to transition my JS code to TS, specifically with a class called Point2D for handling 2 dimensional points. Encountering an error message stating Type 'Function' has no construct signatures.ts(2351). Any insights on what might be going ...

Preventing Multiple Login Attempts in Angular.js Using Typescript

Is there a way to maintain the user login attempts limit even after page refresh? login() { /* Check if user has fewer than 5 failed login attempts */ if (this.failedAttempts < 4) { this.auth.login(this.credentials).subscribe(() => { this.rou ...

Is there a python equivalent for a command that involves sending cookies, making a POST request, and providing authentication information from a JSON file to

The command I have is performing a curl request using data from a JSON file passed to it with the -d option. This method retrieves cookies and saves them in a designated folder. These stored cookies can later be used in subsequent curl requests without ne ...

What causes the difference in behavior between packed and non-packed generics?

When attempting to exclude properties outside of generics, it functions properly but results in a breakdown within the generic context. The issue lies in the fact that Omit<Thing, 'key1' | 'key2'> transforms into Omit<Thing, &a ...

Establishing a default value as undefined for a numeric data type in Typescript

I have a question regarding setting initial values and resetting number types in TypeScript. Initially, I had the following code snippet: interface FormPattern { id: string; name: string; email: string; age: number; } const AddUser = () => { ...

Having trouble retrieving image information within the Asp.net core controller

I am facing an issue trying to store image details in the database through Angular and ASP.NET Core. I am unable to retrieve the image data sent from Angular in the controller. Although I am able to obtain the image information using the [FromForm] attribu ...

How to effectively implement forwardRef with HOC in TypeScript

I'm currently working on developing a React Higher Order Component (HOC), but I've run into some issues along the way. Here's a snippet of my code: import React, { type FC, forwardRef } from 'react' import { ButtonBase, ButtonBaseP ...

issue with emailVerificationRequest function in Next Auth

After integrating nodemailer and handlebars into my application to send a sign-in email using nextauth, I encountered an issue. Upon clicking signIn, the compiler does not enter sendVerificationRequest and no errors are thrown. Here is my [...nextauth] fil ...

Supply additional parameters to the method decorator within an Angular component

Imagine a scenario where there are multiple methods requiring the addition of a confirmation dialog. In order to streamline this process, a custom decorator is created. @Component({...}) export class HeroComponent { constructor(private dialog: MatDialog ...