#set cookie after acstro actions runs

3 messages · Page 1 of 1 (latest)

undone escarp
#

Say you use Astro Actions to submit a form to login or register someone. How do you set a cookie without access to the context object? As far as I know context is only available in middleware and api routes. Normally I'd set a cookie like this from an api route to register or login the user:

context.cookies.set(TOKEN, token, {
    httpOnly: true,
    path: '/',
    maxAge: 60 * 60 * 48, // 48 hours in seconds
    secure: true,
    sameSite: 'none',
    domain: '.site.com',
  })

But with Astro Actions, which I'm calling from a script, I don't think I have access to context or Astro.cookies

idle otterBOT
#

Hi @undone escarp. 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 knowledge sources provided, it seems that you're correct in your understanding that the context object, which includes context.cookies, is not directly accessible within Astro Actions. The context object is primarily available in middleware and API routes.

Astro Actions is a feature that allows you to handle form submissions directly within Astro components. However, the documentation and discussions provided do not mention the ability to set cookies directly from Astro Actions.

If you need to set a cookie after an Astro Action runs, you might need to consider a different approach. One possible solution could be to have your Astro Action call an API route that sets the cookie. This API route would have access to the context object and could set the cookie as you've shown in your example.

Here's how you might set a cookie from an API route:

context.cookies.set(TOKEN, token, {
    httpOnly: true,
    path: '/',
    maxAge: 60 * 60 * 48, // 48 hours in seconds
    secure: true,
    sameSite: 'none',
    domain: '.site.com',
})

(Source: Astro API Reference (https://docs.astro.build/en/reference/api-reference/#cookiesetoptions))

Remember, this is just a suggestion based on the information provided. You might want to check the Astro documentation (https://docs.astro.build/) or their GitHub issues (https://github.com/withastro/astro/issues) for more specific guidance or to see if there have been any updates to Astro Actions that might allow for setting cookies directly.

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