#Pass set-cookie from Supabase to client from action
4 messages · Page 1 of 1 (latest)
Hi @tender bane. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:
To pass a Set-Cookie header from Supabase to the client in an Astro action, you should use Astro's cookie utilities to set the cookie on the response. Astro provides the cookies object (available as Astro.cookies in components/pages or context.cookies in API endpoints and actions) for this purpose.
When you receive authentication tokens (such as access and refresh tokens) from Supabase, you can set them as cookies using cookies.set(). This ensures the cookies are sent to the browser and properly set there.
Here’s an example pattern, adapted for an Astro action or API endpoint:
import type { APIRoute } from "astro";
import { supabase } from "../../../lib/supabase";
export const POST: APIRoute = async ({ request, cookies, redirect }) => {
const formData = await request.formData();
const email = formData.get("email")?.toString();
const password = formData.get("password")?.toString();
if (!email || !password) {
return new Response("Email and password are required", { status: 400 });
}
const { data, error } = await supabase.auth.signInWithPassword({
email,
password,
});
if (error) {
return new Response(error.message, { status: 500 });
}
const { access_token, refresh_token } = data.session;
// Set cookies so they are sent to the client
cookies.set("sb-access-token", access_token, { path: "/" });
cookies.set("sb-refresh-token", refresh_token, { path: "/" });
return redirect("/dashboard");
};
This approach ensures the cookies are included in the response headers and set in the browser. You do not need to manually forward the Set-Cookie header from Supabase; instead, extract the relevant values and use Astro's cookie API to set them for the client Creating auth server endpoints.
If you are working inside an Astro action (using defineAction), the context.cookies object is available in the handler, and you can use it in the same way.
Note: If you need to customize cookie options (e.g., httpOnly, secure, sameSite), you can pass those as the third argument to cookies.set() AstroCookieSetOptions.
If you need to set cookies directly from a Set-Cookie header received from Supabase (for example, if Supabase returns additional cookies), the knowledge sources do not provide a direct method to forward raw Set-Cookie headers. You should extract the values you need and set them using Astro's cookie API.
If you need more advanced handling (such as merging multiple cookies or handling raw headers), refer to the cookies.merge() and cookies.headers() methods.