Last active
July 5, 2023 09:36
-
-
Save balazsorban44/30e2267fe1105529f217acbe3763b468 to your computer and use it in GitHub Desktop.
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() | |
} |
There is an issue ongoing on Vercel #73
I dont use Vercel, I'm on my localhost. Or is that the same?
Vercel is the team who is working on Next.js so it's the same
Oh, thanks
Hey, I tried to use all of this and got this Error:
Code:
import { getToken } from "next-auth/jwt" import { NextResponse } from "next/server" export async function middleware(req) { const session = await getToken({ req, secret: process.env.JWT_SECRET }) const url = req.url if (!session) return NextResponse.redirect("/login") if (url.includes("/login") && session) return NextResponse.redirect("/") return NextResponse.next() }"dependencies": { "@prisma/client": "^3.11.1", "formik": "^2.2.9", "next": "12.1.4", "next-auth": "^4.3.1", "react": "18.0.0", "react-dom": "18.0.0", "yup": "^0.32.11" },
I encouraged the same issue and solved using like that.
const { origin } = req.nextUrl;
return NextResponse.rewrite(`${origin}/login`);
From next js 12.1.4 you need use
return NextResponse.rewrite(new URL('/', request.url));
Example:
import { NextRequest, NextResponse } from 'next/server';
export function middleware(request: NextRequest) {
if (request.nextUrl.pathname === '/about') {
return NextResponse.redirect(new URL('/redirected', request.url));
}
if (request.nextUrl.pathname === '/another') {
return NextResponse.rewrite(new URL('/rewrite', request.url));
}
return NextResponse.next();
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hey, I tried to use all of this and got this Error:
Code: