snippet

How to get cookie from middleware Next.js

Since version 12.1 of Next.js it is possible to use middleware, a practical solution that allows to implement various mechanisms such as authentication verification, analytics and many others.

Here is how to get the content of my cookie "my_cookie_name" to use it in my application.

// My _middleware.js file
import { NextRequest, NextResponse } from 'next/server'

export function middleware(req) {
  let res = NextResponse.next();
  let cookie = req.cookies["my_cookie_name"];
  
  return res;
}