#astro.redirect doesn't work

4 messages · Page 1 of 1 (latest)

coarse nexus
#

My redirect doesn't work in this code

      method: 'POST',
      body: JSON.stringify(body),
      headers: { 'Content-Type': 'application/json' },
    }).then(async (response) => {
      if (response.ok) {
        try {
          const UUID = crypto.randomUUID();
          const startedAt = Math.floor(Date.now() / 1000);
          const maxAge = 60 * 60 * 24;
          const userID = parseInt(await response.text());
          await prisma.sessions.create({
            data: {
              sessionID: UUID,
              startedAt: startedAt,
              endsAt: maxAge,
              userID: userID,
            },
          });
          console.log('cookie set');
          Astro.cookies.set('sessionID', UUID, {
            httpOnly: true,
            maxAge: maxAge,
          });
          return Astro.redirect('https://twitch.tv');
        } catch (error) {}
      }
    });```
tender spadeBOT
#

Hi @coarse nexus. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

Based on the information provided in the extracts, there are a few things you might want to check:

  1. Astro.redirect() usage: According to the Astro documentation (https://docs.astro.build/en/reference/api-reference#astroredirect), Astro.redirect() should be used in a page and not in a child component. The page must return the result of Astro.redirect() for the redirect to occur. Make sure your code is placed in the correct context.

  2. Redirects in Middleware: There is a known bug reported on GitHub (https://github.com/withastro/astro/issues/7484) where cookies are being lost after redirecting using middleware. If you're using middleware and facing issues with cookies, this might be the cause.

  3. Server-side rendering: The context.redirect() function is only available when building for SSR (server-side rendering) and should not be used for static sites as per the Astro documentation (https://docs.astro.build/en/reference/api-reference#contextredirect). Make sure your site is configured for SSR if you're using this function.

  4. Astro version: The ability to pass a status code to Astro.redirect was introduced in Astro 1.5.0 as mentioned in the Astro blog (https://astro.build/blog/astro-150). Make sure you're using a version of Astro that supports this feature if you're using it.

  5. Experimental redirects: Astro 2.6 introduces an experimental feature for redirects. You need to enable the experimental flag experimental.redirects in your project configuration file to use it as mentioned in the Astro blog (https://astro.build/blog/astro-260).

#

If none of these points solve your issue, you might want to provide more context or check the Astro documentation and community for more help.

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: