How to getting Cookies from Express.js to Next.js 14

I’m working on a Next.js 14 application with an Express.js backend. I’m trying to set a JWT token as a cookie after the user logs in, but the cookie is not showing up in the browser’s cookies storage.

Here’s what I did:

1. Backend (Express.js):

I created a /login route where the user logs in. After login, I generate a JWT token and try to store it as a cookie using res.cookie().

Here is my Express.js login route:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>export const login = async (req, res) => {
try {
const { email, password } = req.body;
// User authentication
const user = await AuthService.login(email, password);
// Generate JWT token
const token = generateToken({ id: user._id, email: user.email });
// Set token as cookie
setTokenCookie(res, token);
res.status(200).json({
status: 200,
success: true,
message: 'Login successful',
user: user,
});
} catch (error) {
res.status(400).json({ error: 'Login failed' });
}
};
const setTokenCookie = (res, token) => {
const cookieOptions = {
httpOnly: true, // Cookie not accessible from JavaScript
secure: process.env.NODE_ENV === 'production', // Use secure cookie in production
sameSite: 'lax', // Prevent CSRF attacks
maxAge: 60 * 60 * 1000, // 1 hour
};
res.cookie('authToken', token, cookieOptions);
};
const generateToken = (payload) => {
return jwt.sign(payload, process.env.TOKEN_SECRET, { expiresIn: '1h' });
};
</code>
<code>export const login = async (req, res) => { try { const { email, password } = req.body; // User authentication const user = await AuthService.login(email, password); // Generate JWT token const token = generateToken({ id: user._id, email: user.email }); // Set token as cookie setTokenCookie(res, token); res.status(200).json({ status: 200, success: true, message: 'Login successful', user: user, }); } catch (error) { res.status(400).json({ error: 'Login failed' }); } }; const setTokenCookie = (res, token) => { const cookieOptions = { httpOnly: true, // Cookie not accessible from JavaScript secure: process.env.NODE_ENV === 'production', // Use secure cookie in production sameSite: 'lax', // Prevent CSRF attacks maxAge: 60 * 60 * 1000, // 1 hour }; res.cookie('authToken', token, cookieOptions); }; const generateToken = (payload) => { return jwt.sign(payload, process.env.TOKEN_SECRET, { expiresIn: '1h' }); }; </code>
export const login = async (req, res) => {
  try {
    const { email, password } = req.body;

    // User authentication
    const user = await AuthService.login(email, password);

    // Generate JWT token
    const token = generateToken({ id: user._id, email: user.email });

    // Set token as cookie
    setTokenCookie(res, token);

    res.status(200).json({
      status: 200,
      success: true,
      message: 'Login successful',
      user: user,
    });
  } catch (error) {
    res.status(400).json({ error: 'Login failed' });
  }
};

const setTokenCookie = (res, token) => {
  const cookieOptions = {
    httpOnly: true, // Cookie not accessible from JavaScript
    secure: process.env.NODE_ENV === 'production', // Use secure cookie in production
    sameSite: 'lax', // Prevent CSRF attacks
    maxAge: 60 * 60 * 1000, // 1 hour
  };

  res.cookie('authToken', token, cookieOptions);
};

const generateToken = (payload) => {
  return jwt.sign(payload, process.env.TOKEN_SECRET, { expiresIn: '1h' });
};

2. Frontend (Next.js 14):
I call the /login API from the frontend using fetch. I have set credentials: 'include' to allow the cookie to be saved.
Here’s how I’m making the request:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>const loginUser = async (email, password) => {
const response = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/api/auth/login`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
credentials: 'include', // Allow cookies to be included
body: JSON.stringify({ email, password }),
});
const data = await response.json();
return data;
};
</code>
<code>const loginUser = async (email, password) => { const response = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/api/auth/login`, { method: 'POST', headers: { 'Content-Type': 'application/json', }, credentials: 'include', // Allow cookies to be included body: JSON.stringify({ email, password }), }); const data = await response.json(); return data; }; </code>
const loginUser = async (email, password) => {
  const response = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/api/auth/login`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    credentials: 'include',  // Allow cookies to be included
    body: JSON.stringify({ email, password }),
  });

  const data = await response.json();
  return data;
};

3. Problem:

  • Even though the login request is successful and the backend sends the Set-Cookie header, I can’t see the authToken in the browser’s cookies under ApplicationCookies.

  • I also checked the Network tab, but the Set-Cookie header is missing.

4. My Setup:
Express.js backend running on localhost:5000 | Next.js frontend running on localhost:3000

I’m using cors with the following configuration

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>app.use(cors({
origin: process.env.CLIENT_URL, // Next.js frontend URL
credentials: true, // Allow cookies
}));
</code>
<code>app.use(cors({ origin: process.env.CLIENT_URL, // Next.js frontend URL credentials: true, // Allow cookies })); </code>
app.use(cors({
  origin: process.env.CLIENT_URL, // Next.js frontend URL
  credentials: true,              // Allow cookies
}));

Why isn’t the cookie (authToken) being saved in the browser ?

Any help would be appreciated! Thank you!

I checked that secure: false is used in development.

I made sure credentials: ‘include’ is added in the frontend fetch request.
I verified the res.cookie() is being called on the backend and that the token is generated correctly.

I checked that CORS is configured to allow cookies.

New contributor

ferhatkefs is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật