TanStackT
TanStackโ€ข11mo agoโ€ข
12 replies
sour-pink

Redirect and set cookie from server function called in loader

Hi,

I have a page that validates a token from an email link and then sets a cookie and redirects to a page the user now has access to. You can imagine this would work similar to an "magic link" email based auth system.

When I try to set the cookie and redirect from the server function called by the route's
loader
, the cookie seems to never be set.
const exampleServerFn = createServerFn()
  .validator(zodValidator(z.object({ token: z.string() })))
  .handler(async () => {
    const name = "test";
    const cookieValue = "test";

    setCookie(name, cookieValue, {
      expires: getExpirationTime("1 week"),
      secure: process.env.NODE_ENV === "production",
    });

    throw redirect({to: "/page-behind-cookie"});
  });


In my route I have the loader setup to call the server function:
export const Route = createFileRoute("/access-link-from-email")({
  component: RouteComponent,
  validateSearch: zodValidator(z.object({ token: z.string() })),
  loaderDeps: ({ search }) => ({ token: search.token }),
  async loader({ deps: { token }, params: { packetId, slug } }) {

    // i call the server function here!
    await exampleServerFn({
      data: { token },
    });
  },
});


The redirect is working correctly, however, no cookie is being set. I have tried a few combinations with setting headers as explicitly like so:
setHeader('Set-Cookie', getWebRequest()?.headers.getSetCookie())


Or as part of the redirect but neither seem to be working since the getSetCookie() returns an empty array while being called after setCookie():
throw redirect({
  to: "/page-behind-cookie",
  headers: {
    "Set-Cookie": getWebRequest()?.headers.getSetCookie().join(','),
  }
});


I have also tried calling the server function from the route's
beforeLoad
but that did not work either.

Would love to know if I'm missing something or if this is not supposed to work, any workarounds you'd suggest. Thanks in advanced.
Was this page helpful?