How to send cookies with Fetch API in Next.js 13.4 middleware for authorization? – Cookies

by
Alexei Petrov
authorization cookies fetch-api next.js13

Quick Fix: Utilize ‘Authorization’ header instead of credentials: \"include\" in the fetch() request to pass cookies for authorization in Next.js 13.4 middleware.

The Problem:

In Next.js 13.4, the Fetch API is used for authorization since Axios cannot be utilized in the middleware. However, cookies are not being sent to the server by Fetch, despite the credentials: include option being set. The Nest.js backend has CORS configured with all the necessary headers, including Access-Control-Allow-Credentials. How can cookies be effectively sent with Fetch to enable authorization in Next.js middleware?

The Solutions:

Solution 1: Reassign the Authorization Token to Fetch Header

The Next.js middleware operates solely on the server, which lacks the cookie mechanism present in browsers. Consequently, the credentials: "include" option fails to function as intended. Instead, you need to assign the authorization token explicitly to the header of the fetch request. Here’s how you can achieve this:

export async function middleware(request: NextRequest) {
    const token = request.cookies.get("access_token")?.value || "";

    const res = await fetch("http://localhost:8080/auth/me", {
        headers: {
            Authorization: token
        }
    })

    ...
}

For further information, refer to the Mozilla documentation on the fetch() function: https://developer.mozilla.org/en-US/docs/Web/API/fetch

Q&A

How to send authorization token to backend server in Next.js middleware?

Pass the token in the header of the fetch request.

Why credentials: "include" not working in Nextjs middleware?

Middleware runs on the server, where there are no browser concepts like cookies.

Video Explanation:

The following video, titled "Client and Server Side Cookies in Next.js - YouTube", provides additional insights and in-depth exploration related to the topics discussed in this post.

Play video

Let's learn how to set/remove cookies both in the browser but also on the server in Next.js. This will allow us to ...