Next.js Discord

Discord Forum

Cookie Not Setting After Successful API Login

Unanswered
Chub mackerel posted this in #help-forum
Open in Discord
Chub mackerelOP
I’m working on a Next.js project with a backend service, and I’ve run into an issue where my cookie isn’t being set in the browser, even after a successful login response.

Here’s what I’m doing:

1. I’m sending a POST request to my backend API for user login, which returns a cookie upon successful authentication.
2. The backend response includes the Set-Cookie header with the cookie settings.
3. I’m using the fetch API in a server action on the Next.js frontend to handle the login.

return res
  .cookie("session", session, {
    httpOnly: true,
    secure: process.env.NODE_ENV === "production",
    sameSite: "None",
    path: "/",
    maxAge: session.expires, 
  })
  .status(200)
  .json({ message: "Login successful" });


const response = await fetch(`${process.env.API}/login`, {
  method: "POST",
  credentials: "include",
  headers: {
    "Content-Type": "application/json",
  },
  body: JSON.stringify({ email, password }),
});

1 Reply

can you show the server action? are you importing cookies from next/headers?

import { cookies } from 'next/headers'


cookies().set('session', 'session')