Skip to content

Instantly share code, notes, and snippets.

@MystPi
Created January 2, 2023 19:57
Show Gist options
  • Save MystPi/63cd961017645e1767c09ff22224965b to your computer and use it in GitHub Desktop.
Save MystPi/63cd961017645e1767c09ff22224965b to your computer and use it in GitHub Desktop.
Dynamic URLs with Vercel redirects. Very hacky and should not be used in production.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Greet</title>
</head>
<body>
Hello!
<script src="./paramsToURL.js"></script>
<script>
const nameParam = paramsToURL().get('name');
if (nameParam) {
document.body.innerHTML = `Hello, ${nameParam}!`;
}
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Dynamic URLs</title>
</head>
<body>
<h1>Dynamic URLs with Vercel redirects.</h1>
<p>
Greet the <a href="/greet/world">world</a>, or <a href="/greet">no one</a>
</p>
</body>
</html>
function paramsToURL() {
const urlParams = new URLSearchParams(window.location.search);
const arrayParams = Array.from(urlParams.values());
window.history.replaceState(
null,
'',
`${window.location.pathname}${
arrayParams.length > 0 ? '/' + arrayParams.join('/') : ''
}`
);
return urlParams;
}
{
"cleanUrls": true,
"trailingSlash": false,
"redirects": [
{ "source": "/greet/:name", "destination": "/greet?name=:name" }
]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment