我想要实现的是删除'accessToken'和'refreshToken' cookie,如果accessToken和refreshToken都过期,然后重定向到'/login'路由。
现在这是我的密码
// middleware.ts
import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'
import { verifyAccessToken, verifyRefreshToken } from './utils/checkAuth';
import jwt_decode from "jwt-decode";
import { refreshAccessToken } from './utils/refreshToken';
interface JwtPayload {
email: string
sub: number
iat: number
exp: number
}
export async function middleware(req: NextRequest) {
const accessToken = req.cookies.get('accessToken')?.value;
const refreshToken = req.cookies.get('refreshToken')?.value;
if(accessToken && refreshToken){
const jwtPayload: JwtPayload = jwt_decode(accessToken);
const validToken =
accessToken &&
(await verifyAccessToken(accessToken).catch((err) => {
console.log(err);
}));
if(req.nextUrl.pathname.startsWith('/login') && !validToken){
return
}
if((req.url.includes('/login') || req.url.includes('/register')) && validToken){
return NextResponse.redirect(new URL('/login', req.url));
}
if(!validToken){
try {
const validRefreshToken =
refreshToken &&
(await verifyRefreshToken(refreshToken).catch((err) => {
console.log(err);
}));
if(validRefreshToken){
const newAccessToken = await refreshAccessToken(refreshToken, jwtPayload?.sub);
console.log('GENERATED NEW ACCESS TOKEN', newAccessToken);
// here I want to set accesToken cookie to newAccessToken
} else {
console.log('Refresh token expired');
throw new Error('Refresh token expired')
}
} catch (error) {
console.log('cookies should be deleted');
return NextResponse.redirect(new URL('/login', req.url));
}
}
console.log('TOKEN VALID', accessToken);
} else {
if(req.nextUrl.pathname.startsWith('/login')){
return
} else {
return NextResponse.redirect(new URL('/login', req.url));
}
}
}
// See "Matching Paths" below to learn more
export const config = {
matcher: ['/', '/login', '/register', '/jobs/:path*', '/profile'],
}
我发现通过这样做
const response = NextResponse.next()
response.cookies.delete('accessToken')
response.cookies.delete('refreshToken')
这将起作用,但为了删除cookie,我需要从中间件返回“response”,但我也想将用户重定向到“/login”,如果我返回“response”而不是返回“NextRespons.redirect(newURL('/login',req.url)”,这不会发生
如何删除cookies或设置cookies,然后重定向?
1条答案
按热度按时间new9mtju1#