Created
June 28, 2022 20:25
-
-
Save o-az/68657080dbc7192c223da85c36a228c9 to your computer and use it in GitHub Desktop.
next-auth.js Auth Middleware for Next.js 12.2
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 { NextResponse, type NextRequest } from "next/server"; | |
import { getToken } from "next-auth/jwt"; | |
export const config = { matcher: "/", runtime: "experimental-edge" }; | |
/** | |
* This middleware ensures auth on all routes. | |
* The file should be placed in the root directory of the project. | |
* E.g., /middleware.ts, or /src/middleware.ts | |
* | |
*/ | |
const secret = process.env.NEXTAUTH_SECRET; | |
export default async function middleware(nextRequest: NextRequest) { | |
const absoluteURL = (_: "/login" | "/") => new URL(_, nextRequest.url); | |
const token = await getToken({ | |
req: nextRequest, | |
secret: process.env.NEXTAUTH_SECRET, | |
secureCookie: process.env.NODE_ENV === "production", | |
}); | |
if (!token) return NextResponse.rewrite(absoluteURL("/login")); | |
return NextResponse.rewrite(absoluteURL("/")); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment