How to save cookie on server side in next js through middleware – Server

by
Ali Hasan
azuredevopsserver cookies javascript next.js13 react-server-components

Quick Fix: Utilize the cookies() function provided by Next.js. Inside the middleware, set cookies via response.cookies.set() by providing key-value pairs and necessary options.

The Problem:

In Next.js, it is possible to retrieve cookies on the server side using middleware. However, it is unclear how to save a cookie on the server side so that it can be used in server components. Provide a solution that demonstrates how to save a cookie on the server side in Next.js using middleware.

The Solutions:

Solution 1: Utilize `cookies()` function to set cookies on the server-side

The `cookies()` function, available as part of `next/server`, provides an interface to manipulate cookies directly from the server-side. This function is only available within a Server Action or Route Handler. This directly contrasts with the commonly used `getCookie()` and `setCookie()` methods, which work specifically with client-side cookies.

To use the `cookies()` function effectively, you must first retrieve the `requestStore` variable, specifically the `mutableCookies` property. This is the RequestCookies class instance that allows you to directly interact with cookies. Note that this is a readonly type; if you need to modify cookies, ensure you do so within a Server Action or Route handler.

The `RequestCookies` class offers various methods to manage cookies, such as setting, getting, deleting, and iterating through them. For setting cookies, you can utilize the `set()` method, passing in the cookie name, value, and path as parameters. Deleting cookies is handled by the `delete()` method, which takes either a single cookie name or an array of names as input.

Here’s an example demonstrating how to set and then delete a cookie using the `cookies()` function:

Code Snippet:

import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
     
export function middleware(request: NextRequest) {
  // Setting a cookie with key of 'foo', value of 'bar' and path of '/'
  response.cookies.set({name: 'foo', value: 'bar', path: '/'});
  
  // Deleting the 'foo' cookie
  response.cookies.delete('foo');
  
  // The 'foo' cookie is now deleted
}

This `middleware()` function can be used in `getServerSideProps()` or `getInitialProps()` to set cookies on the server-side, which can then be retrieved and utilized in server components.

Q&A

How can I save a cookie on the server side using middleware in Next.js?

Use cookies().set() function in a Server Action or Route Handler to set a cookie.

What is the RequestCookies class in Next.js?

It represents the cookies received from the client and allows setting, getting, and deleting cookies.

Video Explanation:

The following video, titled "Implement cookie-based Auth in the Next.js 13 App Router - YouTube", provides additional insights and in-depth exploration related to the topics discussed in this post.

Play video

Advanced authentication in NextJs using middleware & server actions. Hamed Bahram•25K views · 16:13 · Go to channel · Progressively Enhanced ...