Skip to content

Instantly share code, notes, and snippets.

@mhaecal
Created July 19, 2022 08:25
  • Star 8 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save mhaecal/f6acdfb108080fdce44e4c2f3eead306 to your computer and use it in GitHub Desktop.
Protected Routes Middleware NextJS 12
import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'
export function middleware(req: NextRequest) {
// get cookie token
const hasToken = req.cookies.get('token')
// protected routes (admin routes)
if (req.nextUrl.pathname.startsWith('/admin')) {
if (hasToken) {
return NextResponse.next()
} else {
return NextResponse.redirect(new URL('/login', req.url))
}
}
// login & register routes
if (['/login', '/register'].includes(req.nextUrl.pathname)) {
if (hasToken) {
return NextResponse.redirect(new URL('/admin/dashboard', req.url))
} else {
return NextResponse.next()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment