Session Cookie Managment betweent Next JS App client and Express Server
First Request:
- The client sends a request to the Express server.
- The Express server responds to the request and sets a cookie named connect.sid with a unique identifier.
- This cookie is sent to the client as part of the response header.
- If the client is making a direct API call (e.g., from a browser or Postman), the browser automatically interprets the Set-Cookie header and stores the connect.sid cookie in its cookie storage.
Subsequent Requests:
- For subsequent requests to the Express server, the client should include the connect.sid cookie in the request header.
- The Express server receives the request and identifies the session associated with the connect.sid cookie.
- The Express server manages the session appropriately based on the information stored in the session data.
- If the connect.sid cookie is not sent back to the Express server in subsequent requests, the request is considered a new session, and a new session will be created.
Sending the first request
The middleware.ts file acts as an entry point for all requests in the sc_storefront_app. It intercepts each request and sends it to a custom router API, api/cookie, which in turn communicates with the Express server API to retrieve the response information. This response includes the connect.sid cookie, which is crucial for session management. The middleware.ts file plays a vital role in ensuring that the connect.sid cookie is properly handled for both initial and subsequent requests. It serves as a central hub for managing cookies and maintaining session consistency throughout the application. Here’s a summary of the process:- A request enters the sc_storefront_app.
- The ts intercepts the request.
- The ts sends the request to the custom router API api/cookie.
- The api/cookie API communicates with the Express server API.
- The Express server API responds with the requested information and the sid cookie.
- The api/cookie API receives the response and relays it back to the ts.
- The ts processes the response and sets the connect.sid cookie in the client’s browser storage if necessary.
- The request proceeds to its intended destination.
middleware.ts
import { NextResponse } from'next/server';
import type { NextRequest } from 'next/server';
if(!cookies.has('connect.sid')){
const cookieResponse = await fetch('http://localhost:3000/api/cookie', {
method: 'GET',
credentials: 'include',
cache: 'no-store'
});
const cookieFromResponse = cookieResponse.headers.get('set-cookie');
// Once we get a response from Router (api/cookie) set it in browser
let modifiedResponse = NextResponse.next();
modifiedResponse.cookies.set(
cookieName, decodeURIComponent(cookievalue)
.....);
import { NextResponse } from'next/server';
import type { NextRequest } from 'next/server';
if(!cookies.has('connect.sid')){
const cookieResponse = await fetch('http://localhost:3000/api/cookie', {
method: 'GET',
credentials: 'include',
cache: 'no-store'
});
const cookieFromResponse = cookieResponse.headers.get('set-cookie');
// Once we get a response from Router (api/cookie) set it in browser
let modifiedResponse = NextResponse.next();
modifiedResponse.cookies.set(
cookieName, decodeURIComponent(cookievalue)
.....);
Router.ts (api/cookie)
Router.ts (api/cookie)
import { cookies } from 'next/headers';
let apiURL = "http://localhost:3004/site/sc/serverconfig";
const response = await fetch(apiURL,
{
credentials: "include",
cache : "no-store"
});
let setCookieArrayNew = response.headers.getSetCookie();
// parse the cookie and extract required information
//Remember to set the cookie back to response
cookies().set({
name: cookieName,
decodeURIComponent(decodeURIComponent(cookieValue)),
......});
Extracting cookies from Browser in Client Side
The browser cookies can be fetch from NextRequest . This code should be placed in middleware.ts
const { cookies } = request;
if(!cookies.has('connect.sid')){
....
}
Express Server Configuration
In the Express middleware configuration (or app.js), make sure to include the following configuration for session management using MongoDB.
const express = require("express");
const app = express();
const session = require("express-session");
const cookieParser = require("cookie-parser");
const MongoStore = require('connect-mongo')
app.use(cors());
app.use(cookieParser())
app.use(
session({
secret: 'sessionSecret', // Replace with a strong secret key
resave: false,
httpOnly: true,
saveUninitialized: true,
store: MongoStore.create({ mongoUrl: "mongodb+srv://.../snippetcommerce" }),
cookie: {
domain: 'localhost',
path: '/',
maxAge: 5000 * 60, //5 mnt
sameSite: 'lax' // Please use your own value based on requirements.
}
})
);