Last active
July 18, 2025 03:03
-
-
Save supersonictw/34129b3e041286947cb89b014e53a43a to your computer and use it in GitHub Desktop.
Generating SPA routes for NGINX to respond status code 404 correctly.
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
// generate-spa-nginx-routes.js | |
// SPDX-License-Identifier: MIT (https://ncurl.xyz/s/Kkn2DQsNR) | |
// nginx.conf example: | |
// | |
// include routes_params; | |
// ... | |
// location / { | |
// try_files $uri $uri/ $routes =404; | |
// } | |
// ... | |
// | |
import {writeFileSync} from 'node:fs'; | |
import {routes} from './src/router/index.js'; | |
const escapeRegExp = (str) => | |
str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); | |
let mapContent = `# Auto-generated by generate-spa-nginx-routes.js | |
map $uri $routes { | |
\tdefault ""; | |
`; | |
routes.forEach((route) => { | |
if (route.path.includes(':pathMatch')) { | |
return; | |
} | |
if (route.path.includes(':')) { | |
const pattern = `^${route.path. | |
replace(/:[^/]+/g, '[^/]+'). | |
replace(/\/?$/, '')}(/)?$`; | |
mapContent += `\t~${pattern} /index.html;\n`; | |
return; | |
} | |
const pattern = `^${escapeRegExp( | |
route.path.replace(/\/?$/, ''), | |
)}(/)?$`; | |
mapContent += `\t~${pattern} /index.html;\n`; | |
}); | |
mapContent += '}\n'; | |
const routesFilePath = new URL( | |
'routes_params', | |
import.meta.url, | |
); | |
writeFileSync(routesFilePath, mapContent); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment