Created
January 11, 2025 20:35
-
-
Save axelrindle/1d76618caf84d62caba429adf5381f56 to your computer and use it in GitHub Desktop.
Next.js dynamic runtime config
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @param {import("next").NextConfig} original | |
*/ | |
export default function makeConfig(original) { | |
const copy = Object.assign({}, original) | |
const apiUrl = new URL(process.env.API_URL) | |
copy.images.remotePatterns = [ | |
{ | |
protocol: apiUrl.protocol.substring(0, 4), | |
hostname: apiUrl.hostname, | |
port: apiUrl.port, | |
pathname: '/storage/**', | |
}, | |
] | |
return copy | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { log } from 'node:console' | |
import { cpSync, existsSync, readFileSync, writeFileSync } from 'node:fs' | |
const fileSource = '.next/standalone/server.js' | |
const fileBackup = `${fileSource}.bak` | |
if (!existsSync(fileBackup)) { | |
cpSync(fileSource, fileBackup) | |
} | |
const contents = readFileSync(fileBackup) | |
const input = contents.toString('utf-8') | |
const lines = input.split('\n') | |
// add import | |
let lastImportLine = 0 | |
for (let i = 0; i < lines.length; i++) { | |
const line = lines[i] | |
if (line.startsWith('import')) { | |
lastImportLine = i | |
continue | |
} | |
} | |
lines.splice(lastImportLine + 1, 0, 'import makeConfig from \'./make-config.js\'') | |
// modify config statement | |
let configLine = 0 | |
for (let i = 0; i < lines.length; i++) { | |
const line = lines[i] | |
if (line.startsWith('const nextConfig')) { | |
configLine = i | |
continue | |
} | |
} | |
const config = /(?:const\s+nextConfig\s*=\s*)(?<config>.*)/gm.exec(lines[configLine]) | |
lines[configLine] = `const nextConfig = makeConfig(${config?.groups?.config})` | |
writeFileSync(fileSource, lines.join('\n')) | |
log(' >> Modified Next.js default server.js') | |
cpSync('buildSrc/make-config.js', '.next/standalone/make-config.js', { force: true }) | |
log(' >> Installed config modification script') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment