Skip to content

Middleware: reading cookies from request returns undefined on static page #11023

@thomasledoux1

Description

@thomasledoux1

Astro Info

Astro                    v4.7.1
Node                     v18.17.1
System                   macOS (x64)
Package Manager          npm
Output                   hybrid
Adapter                  @astrojs/vercel/serverless
Integrations             @astrojs/tailwind
                         @astrojs/react
                         auto-import
                         @astrojs/code-snippets
                         @astrojs/mdx
                         astro:db
                         @astrojs/db/file-url
                         @astrojs/sitemap

If this issue only occurs in one browser, which browser is a problem?

No response

Describe the Bug

At the moment, I am using the hybrid mode of Astro.
I want to redirect requests to my homepage when a certain cookie is part of the request.
When I try to read the cookies from the request to the homepage in middleware, I get back undefined.

import { defineMiddleware } from "astro:middleware";

// `context` and `next` are automatically typed
export const onRequest = defineMiddleware(async (context, next) => {
  const response = await next();
  const featureFlagOverrideCookie = context.cookies.get(
    "vercel-flag-overrides",
  )?.value;
  console.log(featureFlagOverrideCookie); // returns undefined
  if (featureFlagOverrideCookie && context.url.pathname === "/") {
    const decryptedFlags = (await decrypt(featureFlagOverrideCookie)) as {
      newFeature: boolean;
    };
    if (decryptedFlags.newFeature) {
      return context.redirect("/homepage-alternative-feature-flag");
    }
  }
  return response;
});

My homepage is statically rendered.
Once I add export const prerender = true to my homepage, I am able to read the cookies correctly.
I thought it was strange that the behaviour of middleware is dependent on the page you're trying to access?
I would expect to be able to intercept the request to static pages too and read cookies/headers from them.
If this is not possible for technical reason, I couldn't really find this in the documentation, so maybe then it could be made clearer there?

What's the expected result?

Either updated docs on what you can/can't read in middleware, or a fix to be able to read the cookies/headers when requesting a static page.

Link to Minimal Reproducible Example

https://github.com/thomasledoux1/website-thomas-astro/tree/feature-flags-vercel-toolbar

Participation

  • I am willing to submit a pull request for this issue.

Metadata

Metadata

Assignees

No one assigned

    Labels

    needs triageIssue needs to be triaged

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions