[🐛 Bug]: Failed to read header in page ...

I am trying to set a response header in the middleware and read it in pages or layout routes. But this isn't working. I have filed a bug report here - #797 Quick summary in the thread
GitHub
[🐛 Bug]: Failed to read header in page / layout after setting it in...
next-on-pages environment related information System: Platform: darwin Arch: arm64 Version: Darwin Kernel Version 23.5.0: Wed May 1 20:14:38 PDT 2024; root:xnu-10063.121.3~5/RELEASE_ARM64_T6020 CPU...
1 Reply
cj
cjOP6mo ago
Here is a quick summary 1. I set the header in the middleware
import { NextRequest, NextResponse } from 'next/server';

export async function middleware(request: NextRequest) {
const nextResponse = NextResponse.next();
const token = 'token-value';
nextResponse.headers.set('X-CSRF-Token', token);
console.log(`1. middleware: ${token}`);
return nextResponse;
}
import { NextRequest, NextResponse } from 'next/server';

export async function middleware(request: NextRequest) {
const nextResponse = NextResponse.next();
const token = 'token-value';
nextResponse.headers.set('X-CSRF-Token', token);
console.log(`1. middleware: ${token}`);
return nextResponse;
}
Then try reading it in layout.tsx or page.tsx
import type { Metadata } from "next";
import { Inter } from "next/font/google";
import "./globals.css";
import { headers } from "next/headers";

const inter = Inter({ subsets: ["latin"] });

export const metadata: Metadata = {
title: "Create Next App",
description: "Generated by create next app",
};

export default function RootLayout({
children,
}: Readonly<{
children: React.ReactNode;
}>) {
const csrfToken = headers().get('X-CSRF-Token');
console.log(`3. layout: ${csrfToken}`);

return (
<html lang="en">
<body className={inter.className}>{children}</body>
</html>
);
}
import type { Metadata } from "next";
import { Inter } from "next/font/google";
import "./globals.css";
import { headers } from "next/headers";

const inter = Inter({ subsets: ["latin"] });

export const metadata: Metadata = {
title: "Create Next App",
description: "Generated by create next app",
};

export default function RootLayout({
children,
}: Readonly<{
children: React.ReactNode;
}>) {
const csrfToken = headers().get('X-CSRF-Token');
console.log(`3. layout: ${csrfToken}`);

return (
<html lang="en">
<body className={inter.className}>{children}</body>
</html>
);
}
This works as expected when using a node environment (next dev) but when running on miniflare the headers are null (wrangler pages dev)
Want results from more Discord servers?
Add your server