Cookies not accessible when I fetch in Astro frontmatter

29 views Asked by At

Astro Info

Astro                    v4.4.15
Node                     v18.18.0
System                   Windows (x64)
Package Manager          pnpm
Output                   server
Adapter                  @astrojs/cloudflare
Integrations             @astrojs/tailwind
                         @qwikdev/astro
                         astro-compressor
                         @astrojs/react

Describe the Bug

I have enabled Astro SSR. This is my astro file

---
import Layout from "@layouts/Layout.astro";
import { generateCSRFToken } from "@modules/common";

const csrfToken = await generateCSRFToken();

const res = await fetch(import.meta.env.PUBLIC_DOMAIN + "/api/data", {
  headers: {
    "X-CSRF-Token": csrfToken,
  },
});
const result = await res.json();
---

<Layout title="Welcome to Astro.">
  <section>
result : {result}
  </section>
</Layout>

The generateCSRFToken function will send another fetch request which looks like this

import type { APIRoute } from "astro";
import CryptoJS from "crypto-js";
import { setCookie } from "@modules/common";

export const GET: APIRoute = async ({ cookies, request }) => {
  const csrfToken = CryptoJS.lib.WordArray.random(36).toString(
    CryptoJS.enc.Base64
  );

  setCookie(cookies, "X-CSRF-Token", csrfToken, false, "/", 1);

  return new Response(JSON.stringify({ csrfToken }), {
    status: 200,
  });
};

The issue is that if I try to access the cookie value by using cookies.get in the GET request, I got the value but if I do the cookies.get in the front matter or the middleware.ts, I'm not able to get the value. So, my temporary resort is to move the fetch request to the script tag which solves the issue of not being able to access the cookies values after sending the GET request.

Link to Minimal Reproducible Example

https://stackblitz.com/edit/github-9qeh1c?file=src%2Fpages%2Findex.astro

After sending a GET request in the frontmatter which sets the cookie value, I want to be able to access the value of the cookie being set previously in the frontmatter.

1

There are 1 answers

0
Chi Hao On

My current solution to achieve what I wanted (send GET request) in frontmatter.

---
import Layout from "@layouts/Layout.astro";
import { GET } from "../api/generateCSRFToken";
import { GET as GET2 } from "../api/data"

const result1 = await GET(Astro);
const { csrfToken } = await result1.json();

Astro.request.headers.set("X-CSRF-Token", csrfToken);
const res2 = await GET2(Astro);

const result = await res2.json();
console.log(result)
---