'DRY way to authenticate several pages in Nextjs?
I understand in the page component I can do something like
if(!isAuthenticated){
router.replace("/login")
}
But if 95% of my routes require a login, what's the best way to DRY this up, so I don't have to put this if statement on all my pages. I looked into middleware but because that runs on the server-side, I can't access the app state.
I'm new to React and Nextjs. I come from an angular background where this would be solved with a route guard, is there anything like this in Nextjs?
Solution 1:[1]
You should use Middleware
If your Middleware is created in /pages/_middleware.js, it will run on all routes within the /pages directory.
For more info read the official page
Solution for js
import { NextResponse } from 'next/server'
export async function middleware(req, ev) {
// req: contains request information
if (!isAuthenticated()) {
return NextResponse.redirect('/login');
}
return NextResponse.next();
}
Solution for ts
import type { NextFetchEvent, NextRequest } from 'next/server'
import { NextResponse } from 'next/server'
export function middleware(req: NextRequest, ev: NextFetchEvent) {
if (!isAuthenticated()) {
return NextResponse.redirect('/login');
}
return NextResponse.next();
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
