Reputation: 83
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.
Upvotes: 3
Views: 3713
Reputation: 131
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
Upvotes: 7