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

Utilizing React Typescript Discriminating Unions to choose between two different types based solely on props

In my project, I have a component that consists of different types: type Base = { color: string } type Button = { to: string } & Base type Link = { link: string linkNewTab: boolean } & Base type ComponentProps = Button | Link e ...

Attempting to connect to "http://localhost:4242/webhook" was unsuccessful due to a connection refusal when trying to dial tcp 127.0.0.1:4242

In my next.js 13 project, I am integrating stripe with TypeScript and configuring the app router. To create a stripe event in my local machine, I ran stripe listen --forward-to localhost:4242/webhook, but now I am encountered with the error message stripe ...

Managing database downtime with TypeORM

In the event that my MSSQL server experiences a crash and an app client makes a request to the API, the current behavior is for it to endlessly spin until Express times out the unanswered request. By enabling logging in TypeORM, I am able to observe the e ...

Unfortunately, the utilization of an import statement outside a module is restricted when working with Electron

Is there a solution to the well-known problem of encountering the error message "Cannot use import statement outside a module" when working with an Electron-React-Typescript application? //const { app, BrowserWindow } = require('electron'); impor ...

Having difficulty passing a function as a parameter from a NextJS component

I have a code snippet like this in a NextJS component: const [currentGPS, setCurrentGPS] = useState({coords:{latitude:0.0,longitude:0.0}}) useEffect(() => { utl.getGPSLocation( (v:{coords: {latitude:number; longitude:n ...

Guide to implementing scheduled tasks in a Node.js API using Express

Currently, my Node API has multiple endpoints, and while they work well for the most part, there is one endpoint that struggles with processing large requests taking up to 1 hour. To handle this, I am considering implementing a system where instead of wait ...

Firebase Operation Not Supported Error in next.js (auth/operation-not-supported-in-this-environment)

After successfully deploying a Next.js app hosted on Vercel with Firebase authentication that functions properly for users, I encountered a mysterious error during the "npm run build" phase: FirebaseError: Firebase: Error (auth/operation-not-supported-in ...

The wallet disconnects from the next.js Solana application

After following a YouTube tutorial on creating a Solana application, my code is working fine and the wallet successfully connects. However, upon refreshing the page, the wallet disconnects and the getWallet function returns nothing (connected = false and P ...

What measures can I take to protect this API?

In the process of developing a full-stack application using Next-JS with an API connected to Firebase, my main concern revolves around ensuring the security of this API. Specifically, I am looking for ways to protect a variable called "Premium" stored in F ...

How do I insert a new column into the result set of a query in Prisma?

Imagine a scenario where there are two tables: User, which has fields for name and Id, and Post, which has fields for name and content. These tables are connected through a many-to-many relationship (meaning one post can have multiple users/authors and eac ...

Tips for integrating Excel files with NestJS

I'm in the process of developing a REST API that will utilize a third-party API to retrieve specific status information. The URLs needed for this API are stored in an Excel file, which is a requirement for this use case. My goal is to extract the URLs ...

What are some ways to enhance this TypeScript code using Functional Programming with the FP-TS library?

i am struggling to write some typescript code using fp-ts Below are the tasks that i want the algorithm to carry out: Once a path is received from the command line, it should check if the given path exists search for all files in the directory and locat ...

What could be causing my NodeJS Backend to not retrieve the data properly?

For a current project, I am tasked with building a mobile application using Flutter for the frontend and NodeJS for the backend. To facilitate this, I have acquired a VPS from OVHcloud running Ubuntu 20.04. Following various tutorials, I set up a server as ...

Error encountered during navigation: navigator has not been defined

I encountered an issue where the page gets redirected upon form submission without triggering the catch block. However, in the backend, I am facing an error stating that the API body is not being executed. Below is the code snippet of the page: "use cl ...

Angular is not rendering styles correctly

Having two DOMs as depicted in the figures, I'm facing an issue where the circled <div class=panel-heading largeText"> in the first template receives a style of [_ngcontent-c1], while that same <div> gets the style of panel-primary > .pane ...

Is there a simple method to verify if an element has been properly enabled or disabled upon clicking a checkbox?

I have a component that includes a <Switch/> (using Material-UI) and a <TextField/>. When the user clicks on the Switch, it toggles the enabled/disabled state of another TextField. The code functions correctly, but my JEST test always fails. .. ...

Issue encountered while attempting to run an Angular project using the CLI: "Module not found - Unable to resolve 'AngularProjectPath' in 'AngularProjectPath'"

Just like the title suggests, I'm facing an issue with compiling my angular project. It seems to be having trouble resolving my working directory: Error: Module not found: Error: Can't resolve 'D:\Proyectos\Yesoft\newschool& ...

A more effective way to obtain exclusive information through Next.js

Whenever a user accesses a specific page (e.g. /post/1), I aim to retrieve the data related to post 1. To achieve this, I extract the URL pathname using window.location.pathname (such as /post/1), eliminate the initial characters (/post/) using substring, ...

Issue with updating initial state that is null in Redux Toolkit

Encountered an issue while using Redux Toolkit with Redux Persist. Unable to update the initial state of a user if it's null. The code consistently assigns null to the store regardless of passing parameters. import { createSlice, PayloadAction } from ...

Unable to pass a component property to a styled Material-UI Button

I have customized a MUI Button: const SecondaryButton = styled(Button)<ButtonProps>(({ theme }) => ({ ... })); export default SecondaryButton; When I try to use it like this: <label htmlFor="contained-button-file"> <input ...