Replies: 1 comment 2 replies
-
At the moment, I'm using this: async function isInServerActionContext(): Promise<boolean> {
try {
const resolvedCookies = await cookies();
resolvedCookies.delete("if this delete succeeds, i must be in server action context");
return true;
} catch (error) {
if (
error instanceof Error &&
error.message.includes("Cookies") &&
error.message.includes("nextjs")
) {
// looks like the Next.js's error about cookies being modifiable only in Server Action or Route Handler,
// we are not there.
return false;
}
// some unrelated error happened, let it go
throw error;
}
} |
Beta Was this translation helpful? Give feedback.
2 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
Summary
https://nextjs.org/docs/app/api-reference/functions/cookies api has restrictions: setting or deleting of cookies is only available in Server Action / Route handler, and not on, say, page render.
How do I programmatically detect in which situation I am?
I writing data-fetching code with authentication. If my database API returns 401, I would need to refresh access token, but that is impossible on page render, so instead I need to redirect to login page with
redirect()
. If my server function or route handler call has returned 401, I can refresh access token and try again.I would like to have one
fetchAuth
which does first or second depending on where it was called from, how do I know that?Example
No response
Beta Was this translation helpful? Give feedback.
All reactions