Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can i get next-auth session in nextjs 12 middlware

Tags:

next.js

I was experimenting with the new nextjs features and while using next-auth inside the pages/_middleware.ts this doesn't seem to work

import { getSession } from 'next-auth/client';
import type { NextFetchEvent, NextRequest } from 'next/server'
import {NextResponse} from 'next/server'
async function middleware(req: NextRequest, ev: NextFetchEvent) {
    let session = await getSession({ req });

      return new Response('Auth required', {
        status: 401,
        headers: {
          'WWW-Authenticate': 'Basic realm="Secure Area"',
        },
      })
}
export {middleware}

this works in api routes but the "req" object is NextApiRequest unlike here. so how can i get the user object inside the middleware so i can do a role/authentication check.

like image 492
Maruf Avatar asked Nov 18 '25 04:11

Maruf


1 Answers

What worked for me was to use the helper function getToken() and decrypt the session information from the token which will be sent along with the request, i.e req parameter

Here is a sample of my _middleware.ts

export async function middleware(
  req: NextApiRequest,
  ev: NextFetchEvent
) {
  const token = await getToken({
    req,
    secret: process.env.SECRET,
  });
  console.log("from middleware ", token);
  return NextResponse.next();
}

Note process.env.SECRET refers to the secret you used in your [...nextauth].ts configuration for jwt

like image 145
Kojo Agyeman-Budu Avatar answered Nov 20 '25 18:11

Kojo Agyeman-Budu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!