Remove cookie upon token validation in beforeError hook #681
Replies: 4 comments
-
From the code you provided, it looks like you're deleting the session cookie but then not doing any kind of redirect to the login page. |
Beta Was this translation helpful? Give feedback.
-
I have already done |
Beta Was this translation helpful? Give feedback.
-
My current way to delete token from cookie is that I redirect to fake url and check that url in middleware and handle removing logic by calling server action. Please let me know if you have better solution. Here is the code. export const api = ky.create({
prefixUrl: BASE_URL,
hooks: {
beforeRequest: [injectTokenBeforeRequest],
beforeError: [
async (error) => {
const { response } = error
if (response?.status === 401) {
redirect(/invalid-token)
}
return error
},
],
},
}) // middleware.ts
export async function middleware(request: NextRequest) {
const path = request.nextUrl.pathname
if (path.startsWith("/invalid-token")) {
await deleteSessionToken() // calling server action
return NextResponse.redirect(new URL("/signin", request.nextUrl))
}
return NextResponse.next()
} |
Beta Was this translation helpful? Give feedback.
-
I think the issue is that you are making requests from the client, which can follow redirects but doesn't navigate the page you are on, and then you send it a redirect from the backend. My suggestion is to use Something like: export const api = ky.create({
prefixUrl: BASE_URL,
hooks: {
beforeRequest: [injectTokenBeforeRequest],
beforeError: [
async (error) => {
const { response } = error
if (response?.status === 401) {
await ky.delete('/api/session');
location.assign('/invalid-token');
}
return error
},
],
},
}) |
Beta Was this translation helpful? Give feedback.
-
If status is 401 then, I just want to remove token from cookie and redirect to login page. Don't want to retry agian. I use nextjs.
Beta Was this translation helpful? Give feedback.
All reactions