Next.js Discord

Discord Forum

I wanna redirect to the "auth/signin" if the role of the user is not administrator with middleware

Unanswered
Verin posted this in #help-forum
Open in Discord
import { getSession } from 'next-auth/react'
import { NextResponse, NextRequest } from 'next/server'
// import type { NextRequest } from 'next/server'
// import type { NextRequest } from 'next/server'

export { default } from "next-auth/middleware"

// This function can be marked async if using await inside
export async function middleware(req: NextRequest) {
const requestForNextAuth = {
headers: {
cookie: req.headers.get('cookie'),
},
};

const session = await getSession(req);

if (session.user.role !== "ADMIN") {
return NextResponse.next()
} else {
return NextResponse.redirect(new URL('/auth/signin', request.url))
}

}


// See "Matching Paths" below to learn more
export const config = {
matcher: '/((?!auth|api|_next/static|_next/image|favicon.ico).*)'
}

This is the middleware.ts.
It is for the redirect to the signin page if the role of the user in the session is not admin, redirect to the "auth/sign"

0 Replies