Skip to content

Instantly share code, notes, and snippets.

@ydnar
Last active September 12, 2023 10:14
Show Gist options
  • Save ydnar/afd2fdfa90f9579a8188f0bfe418493d to your computer and use it in GitHub Desktop.
Save ydnar/afd2fdfa90f9579a8188f0bfe418493d to your computer and use it in GitHub Desktop.
Nuxt.js middleware to enable redirects to absolute URLs
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
}
@KarmaBlackshaw
Copy link

where should this be put?

@ydnar
Copy link
Author

ydnar commented Sep 12, 2023

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