Skip to content

Commit

Permalink
Fix autogenerated append to original _headers file (#851)
Browse files Browse the repository at this point in the history
* Fix autogenerated append to original _headers file

Vercel hard links the public directory so when next-on-pages appends to
the vercel output directory, it is also appending to the original
`public/_headers` file too.

This commit fixes the problem by copying the contents to memory before
unlinking the file and creating a new (non-linked) file.

Closes #848
  • Loading branch information
nickbabcock authored Aug 7, 2024
1 parent 3bde1b0 commit 968171a
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 11 deletions.
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

0 comments on commit 968171a

Please sign in to comment.