我想在仅登录然后打开时限制用户主页和管理仪表板,否则重定向到登录或管理员登录页面。
import { NextResponse } from 'next/server'
import { NextRequest } from 'next/server'
// This function can be marked `async` if using `await` inside
export function middleware(request) {
const token= request.cookies.get("token")?.value;
const admintoken= request.cookies.get("admintoken")?.value;
const notLoginInUserNotAccessPathwithAdmin =
request.nextUrl.pathname==="/login"||
request.nextUrl.pathname=="/signup" ;
const notLoginAdminNotAccessPathAdmin=
request.nextUrl.pathname=="/admin";
if(notLoginInUserNotAccessPathwithAdmin){
if(token){
return NextResponse.redirect(new URL('/home', request.url))
}
}else{
if(!token){
return NextResponse.redirect(new URL('/login', request.url))
}
}
if(notLoginAdminNotAccessPathAdmin){
if(admintoken){
return NextResponse.redirect(new URL('/dashboard', request.url))
}
}else{
if(!admintoken){
return NextResponse.redirect(new URL('/login', request.url))
}
}
}
// See "Matching Paths" below to learn more
export const config = {
matcher: ['/users/:path*','/dashboard/:path*','/login','/signup','/admin','/home/:path*'],
}
我想在仅登录然后打开时限制用户主页和管理仪表板,否则重定向到登录或管理员登录页面。
这是我能想到的一种方法。我修改了一些代码以使其更具可读性且易于更改。如果您需要进一步修改,请随时告诉我。
import { NextResponse } from 'next/server'
import { NextRequest } from 'next/server'
export function middleware(request) {
const userToken = request.cookies.get("token")?.value;
const adminToken = request.cookies.get("admintoken")?.value;
const userPaths = ['/home', '/profile', '/user-settings']; // user-specific paths
const adminPaths = ['/dashboard', '/admin-settings']; // admin-specific paths
const isUserPath = userPaths.some(path => request.nextUrl.pathname.startsWith(path));
const isAdminPath = adminPaths.some(path => request.nextUrl.pathname.startsWith(path));
// Redirect to login if user tries to access a protected user path without a user token
if (isUserPath && !userToken) {
return NextResponse.redirect(new URL('/login', request.url));
}
// Redirect to admin login if someone tries to access a protected admin path without an admin token
if (isAdminPath && !adminToken) {
return NextResponse.redirect(new URL('/admin-login', request.url));
}
// If a logged-in user tries to access the login/signup page, redirect them to their home
if (request.nextUrl.pathname === '/login' || request.nextUrl.pathname === '/signup') {
if (userToken) {
return NextResponse.redirect(new URL('/home', request.url));
}
}
// If a logged-in admin tries to access the admin login page, redirect them to the dashboard
if (request.nextUrl.pathname === '/admin-login') {
if (adminToken) {
return NextResponse.redirect(new URL('/dashboard', request.url));
}
}
return NextResponse.next(); // continue with the request as normal if no redirect is required
}
export const config = {
matcher: ['/home/:path*', '/profile', '/user-settings', '/dashboard/:path*', '/admin-settings', '/login', '/signup', '/admin-login'],
};