Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix autogenerated append to original _headers file #851

Merged
merged 3 commits into from
Aug 7, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/breezy-walls-stare.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@cloudflare/next-on-pages': patch
---

Fix autogenerated content also getting appended to the original public/\_headers file
37 changes: 26 additions & 11 deletions packages/next-on-pages/src/buildApplication/buildMetadataFiles.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { join } from 'path';
import { writeFile } from 'fs/promises';
import { writeFile, stat, unlink, readFile } from 'fs/promises';
import { nextOnPagesVersion, readJsonFile } from '../utils';
import { getPhaseRoutes, getVercelConfig } from './getVercelConfig';
import { cliError } from '../cli';
Expand Down Expand Up @@ -40,22 +40,37 @@ async function buildNextStaticHeaders(
);
const nextStaticHeaders = (nextStaticRoute as VercelSource)?.headers;

if (nextStaticHeaders) {
await writeFile(
join(outputDir, '_headers'),
`
if (!nextStaticHeaders) {
return;
}

const headersPath = join(outputDir, '_headers');

const nopContent = `
# === START AUTOGENERATED @cloudflare/next-on-pages IMMUTABLE HEADERS ===
${nextStaticPath}/*
${Object.entries(nextStaticHeaders)
.map(([header, value]) => ` ${header}: ${value}`)
.join('\n')}
# === END AUTOGENERATED @cloudflare/next-on-pages IMMUTABLE HEADERS ===\n`,
{
// in case someone configured redirects already, append to the end
flag: 'a',
},
);
# === END AUTOGENERATED @cloudflare/next-on-pages IMMUTABLE HEADERS ===\n`;

try {
// Vercel hard links the static files directory:
// https://github.com/vercel/vercel/blob/8e20fed/packages/cli/src/util/build/write-build-result.ts#L336
// So we need to unlink before we append data, otherwise we will mutate
// the original file found in the public directory.
const stats = await stat(headersPath);
if (stats.nlink > 1) {
const data = await readFile(headersPath);
await unlink(headersPath);
await writeFile(headersPath, data);
}
} catch (e) {
if ((e as { code?: string }).code !== 'ENOENT') {
throw e;
}
}
await writeFile(headersPath, nopContent, { flag: 'a' });
}

/**
Expand Down
Loading