NextAuth.js Auth Middleware for Next.js 12
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { getToken } from "next-auth/jwt" | |
import { NextResponse } from "next/server" | |
export async function middleware(req) { | |
// return early if url isn't supposed to be protected | |
if (!req.url.includes("/protected-url")) { | |
return NextResponse.next() | |
} | |
const session = await getToken({ req, secret: process.env.SECRET }) | |
// You could also check for any property on the session object, | |
// like role === "admin" or name === "John Doe", etc. | |
if (!session) return NextResponse.redirect("/api/auth/signin") | |
// If user is authenticated, continue. | |
return NextResponse.next() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment