Last active
September 12, 2023 10:14
-
-
Save ydnar/afd2fdfa90f9579a8188f0bfe418493d to your computer and use it in GitHub Desktop.
Nuxt.js middleware to enable redirects to absolute URLs
This file contains 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 url from 'url' | |
import qs from 'qs' | |
export default function (ctx) { | |
fixRedirect(ctx) | |
const { route, redirect } = ctx | |
const { path, query } = route | |
// Redirect trailing slashes, preserving query string: /foo/ -> /foo | |
if (path.length > 1 && path.slice(-1) === '/') { | |
const dest = path.replace(/\/+$/, '') || '/' | |
return redirect(301, dest, query) | |
} | |
// Other redirects | |
if (redirects[path]) { | |
return redirect(301, redirects[path], query) | |
} | |
} | |
const redirects = { | |
'/foo': '/foo/bar', | |
'/baz': '/foo/bar/baz' | |
} | |
// The redirect function in Nuxt/Vue doesn’t support absolute URLs. | |
// https://github.com/nuxt/nuxt.js/issues/770 | |
function fixRedirect (ctx) { | |
const _redirect = ctx.redirect | |
ctx.redirect = function (status, path, query) { | |
// If only 1 or 2 arguments: redirect('/') or redirect('/', { foo: 'bar' }) | |
if (typeof status === 'string' && (typeof path === 'undefined' || typeof path === 'object')) { | |
query = path || {} | |
path = status | |
status = 302 | |
} | |
path = addQuery(path, query) | |
if (!isAbsolute(path)) { | |
_redirect(status, path) | |
} else if (ctx.isServer && ctx.res) { | |
ctx.res.setHeader('Location', path) | |
ctx.error({ statusCode: status, message: `Redirecting to ${path}` }) | |
} else if (ctx.isClient && window && window.location) { | |
window.location = path | |
ctx.error({ statusCode: status, message: `Redirecting to ${path}` }) | |
} | |
} | |
} | |
function isAbsolute (path) { | |
return (path.indexOf('//') === 0 || url.parse(path).protocol) | |
} | |
function addQuery (path, query) { | |
if (!query) { | |
return path | |
} | |
const q = qs.stringify(query) | |
if (q === '') { | |
return path | |
} | |
// Append query string with ? or & if a querystring already exists | |
path = path + (path.indexOf('?') > 0 ? '&' : '?') + q | |
return path | |
} |
where should this be put?
I’m pretty sure this doesn’t work with Nuxt 3. Sorry!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
ctx.isServer
andctx.isClient
should be replaced withprocess.server
andprocess.client