Koobz866
Koobz866

Reputation: 196

Next.js cookies aren't coming through on router middleware

I'm attempting to create some route guarding using the new Next.Js 12 middleware feature. My authentication is based on a JWT token set on a cookie. I had previously implemented this using the API backend on Next.Js with no issues, and still when hitting the API routes the cookie will persist on the request no problem.

My issue appears when it will request a static page from the server. No cookies are attached so I can not determine if a User is authenticated and always redirect to a log in page. So for example the request to http://localhost:3000/ (Homepage) will not send any cookies to the middleware. But, http://localhost:3000/api/user will send a cookie to the middleware. Is there a setting I have missed in the documentation to allow this to happen?

Not sure if at all helpful but here is my _middleware.ts file that sits on the root of the pages.

import type { NextFetchEvent, NextRequest } from 'next/server';
import { NextResponse } from 'next/server';

const middleware = (req: NextRequest, ev: NextFetchEvent) => {
  console.log(req.cookies);
  console.log(req.cookies['user']);
  console.log(req.nextUrl.pathname);
  if (req.nextUrl.pathname === '/') {
    return NextResponse.redirect('http://localhost:3000/login');
  }
};

export default middleware;

Upvotes: 10

Views: 6210

Answers (3)

Abolfazl Roshanzamir
Abolfazl Roshanzamir

Reputation: 14792

To check if the cookie exists

request.cookies.has('YOUR_COOKIE_NAME')

To get the cookie value

request.cookies.get('YOUR_COOKIE_NAME')?.value

Upvotes: 0

Yilmaz
Yilmaz

Reputation: 49321

Next.js > 12.2

req.cookies.get("user")

Before Next.js 12.2,

req.cookies?.user

Upvotes: 6

111
111

Reputation: 1

I had a same problem. I use tag for routing and it works but im not sure that it is a good choice.

Upvotes: 0

Related Questions