Created
July 19, 2022 08:25
-
-
Save mhaecal/f6acdfb108080fdce44e4c2f3eead306 to your computer and use it in GitHub Desktop.
Protected Routes Middleware NextJS 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 { 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