NextJS删除cookie并从中间件重定向

ctehm74n  于 2023-06-29  发布在  其他
关注(0)|答案(1)|浏览(223)

我想要实现的是删除'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,然后重定向?

new9mtju

new9mtju1#

const response = NextResponse.redirect(new URL('/login', req.url))
response.cookies.delete('accessToken')
response.cookies.delete('refreshToken')
return response

相关问题