Skip to content

Instantly share code, notes, and snippets.

@o-az
Created June 28, 2022 20:25
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save o-az/68657080dbc7192c223da85c36a228c9 to your computer and use it in GitHub Desktop.
Save o-az/68657080dbc7192c223da85c36a228c9 to your computer and use it in GitHub Desktop.
next-auth.js Auth Middleware for Next.js 12.2
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