Using Next Auth Request in NextJS Middleware

I was working on a Next.js project that involved authentication. I relied on the next-auth (updated to authjs) to handle authentication. The library is amazing and has so many drivers and adapters. However, since I am using TypeScript, I had some difficulties dealing with it.

Within the file middleware.ts I was intercepting the request to check if the current user is allowed to enter a specific URL.

middleware.ts
import authConfig from '@/auth.config';
const { auth } = NextAuth(authConfig);
export default auth(req => {
	// ... middleware body
});

The problem was the type of the req parameter. Typescript was giving the following error:

Parameter ‘req’ implicitly has an ‘any’ type ….

I believe you saw that error a lot 🙂

The req parameter is expected to be of type NextAuthRequest. However, the library is not exporting that type, I explored it and found the type definition which is just extending the NextRequest by adding auth to it this way:

node_modules/next-auth/lib/index.d.ts
export interface NextAuthRequest extends NextRequest {
    auth: Session | null;
}

I think you know what to do now 🙂 yes, you just have to do the same, copy that type definition to your middleware, and do not forget to set the response type as well, so my middleware.ts file became like so:

middleware.ts
import NextAuth, { Session } from 'next-auth';
import authConfig from '@/auth.config';
import { NextRequest } from 'next/server';
const { auth } = NextAuth(authConfig);
export default auth(
	(req: NextRequest & { auth: Session | null }): Response | void => {
		// ... middleware body
});

Hope this will solve your issue, until the library has an update

Leave a Reply

Your email address will not be published. Required fields are marked *