正在开发 Next.js 应用程序,我使用中间件来检查用户的令牌是否已过期。如果令牌已过期,我想清除并删除 cookie 并将用户重定向到登录页面。这是我的代码的相关部分:
export async function middleware(request: NextRequest) {
const path = request.nextUrl.pathname;
const token = request.cookies.get('token')?.value || '';
const url = `${process.env.NEXT_PUBLIC_BASE_URL}users/auth/check-token-expiration`;
let tokenExpirationData;
try {
const response = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
token,
}),
});
if (response.ok) {
tokenExpirationData = await response.json();
console.log(tokenExpirationData?.data);
} else {
console.error('Error occurred while fetching data:', response.statusText);
}
} catch (error) {
console.error('Error occurred:', error);
}
if (path !== '/login' && tokenExpirationData && tokenExpirationData.data) {
request.cookies.clear();
request.cookies.delete('token'); // This line doesn't work as expected
return NextResponse.redirect(new URL('/login', request.nextUrl));
}
}
在上面的代码中,我试图在用户的令牌过期时清除并删除“令牌”cookie。但是, request.cookies.delete('token') 行似乎没有删除 cookie。即使令牌过期后,用户仍然可以访问受限页面。
我已经检查了逻辑,它正确地识别了令牌何时过期并触发重定向到登录页面。但是删除cookie不起作用。
这可能是什么问题?我在实施中遗漏了什么吗?任何帮助将不胜感激。
问题是因为您删除了错误的 cookie。
从您的代码片段中,您将从
request
中删除 cookie,但这对从中间件返回的实际 cookie 没有影响。
您想要做的是从
response
对象中删除 cookie。像这样:
// create the response object
const response = NextResponse.redirect(new URL('/login', request.url))
// Delete the token cookie
response.cookies.delete('token')
// Return the response
return response