Z I P T E C H

Session Cookie Handling with Next JS Client and Express Server

Session Cookie with Next JS Client and Express server

Session Cookie Managment betweent Next JS App client and Express Server

First Request:

  1. The client sends a request to the Express server.
  2. The Express server responds to the request and sets a cookie named connect.sid with a unique identifier.
  3. This cookie is sent to the client as part of the response header.
  4. 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.
In the case of Server-Side Rendering (SSR), the client application is responsible for extracting the connect.sid cookie from the response header and setting it in browser cookie storage.

Subsequent Requests:

  1. For subsequent requests to the Express server, the client should include the connect.sid cookie in the request header.
  2. The Express server receives the request and identifies the session associated with the connect.sid cookie.
  3. The Express server manages the session appropriately based on the information stored in the session data.
  4. 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:
  1. A request enters the sc_storefront_app.
  2. The ts intercepts the request.
  3. The ts sends the request to the custom router API api/cookie.
  4. The api/cookie API communicates with the Express server API.
  5. The Express server API responds with the requested information and the sid cookie.
  6. The api/cookie API receives the response and relays it back to the ts.
  7. The ts processes the response and sets the connect.sid cookie in the client’s browser storage if necessary.
  8. The request proceeds to its intended destination.
This mechanism ensures that the connect.sid cookie is properly handled for both initial and subsequent requests, enabling seamless session management throughout the sc_storefront_app.

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)
          .....);
Please note that decodeURIComponent is used to decode the value of the cookie.

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)),
                 ......});
Double decoding is employed to address cookie tampering concerns and ensure that the connect.sid cookie received by the Express server matches the one generated by the server. This is particularly useful when dealing with potential inconsistencies arising from frameworks like Next.js 13/14.

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.
            }
          })
        );
Please note that when a session is established, the session information will be stored in the MongoDB “session table”. A sample session record is provided below.    
Related Tags:
Social Share:

Leave A Comment