jwt-next-auth v2.0.0
Implement JWT authentication using NextJS (>= v14) middleware and API routes.
How to use
Create a lib
folder with a file called jwtAuthClient.ts
and call the createAuthClient
function.
// lib/jwtAuthClient.ts
import { createJWTAuthClient } from 'jwt-auth-next';
export default createJWTAuthClient({
// ... options
});
Create an API route in the app
directory to handle refreshing the access token if required.
// app/api/auth/refresh-token/route.ts
import jwtAuthClient from '@/lib/jwtAuthClient';
const handler = jwtAuthClient.handlers.validateTokenCookiesHandler;
export { handler as POST };
Create a middleware.ts
file in the root directory and add the following:
// middleware.ts
import { NextRequest, NextResponse } from 'next/server';
import jwtAuthClient from './lib/jwtAuthClient';
export async function middleware(req: NextRequest) {
const res = NextResponse.next();
return jwtAuthClient.handlers.refreshTokenMiddleware(
{ req, res },
{
// ... event handlers
}
);
}
export const config = {
matcher: [
// ... all routes EXCEPT 'api/**/*'
],
};