This repository was archived by the owner on Sep 3, 2024. It is now read-only.

Description
What problem does this feature solve?
This is maybe an edge-case, and the point of nuxt.config.js' router.base is for when a Web server will serve Nuxt elsewhere than the domain root.
But when in local development, hitting localhost, when router.base is not / returns a 404.
What does the proposed changes look like?
We can use that situation to document how nuxt hooks works.
NOTE I have a functioning connect middleware, . Let's add this to the docs.
How to use example
PS: In the gist, I've added comments.
-
Setup Nuxt config
// file: nuxt.config.js
import hooks from './hooks'
export default {
router: {
base: '/portal',
},
hooks: hooks(this),
}
-
Hooks module setup
// file: hooks/index.js
import render from './render'
export default (nuxtConfig) => ({
// e.g. 'render:context'
render: render(nuxtConfig),
})
-
Render hooks module
// file: hooks/render.js
import redirectRootToPortal from './route-redirect-portal'
export default (nuxtConfig) => {
const router = Reflect.has(nuxtConfig, 'router') ? nuxtConfig.router : {}
const base = Reflect.has(router, 'base') ? router.base : '/portal'
return {
setupMiddleware(app) {
app.use('/', redirectRootToPortal(base))
},
},
}
-
Middleware code
// file: hooks/route-redirect-portal.js
import parseurl from 'parseurl'
export default (desiredContextRoot) => function projectHooksRouteRedirectPortal(req, res, next) {
const desiredContextRootRegExp = new RegExp(`^${desiredContextRoot}`)
const _parsedUrl = Reflect.has(req, '_parsedUrl') ? req._parsedUrl : null
const url = _parsedUrl !== null ? _parsedUrl : parseurl(req)
const startsWithDesired = desiredContextRootRegExp.test(url.pathname)
const isNotProperContextRoot = desiredContextRoot !== url.pathname
if (isNotProperContextRoot && startsWithDesired === false) {
const pathname = url.pathname === null ? '' : url.pathname
const search = url.search === null ? '' : url.search
const Location = desiredContextRoot + pathname + search
res.writeHead(302, {
Location,
})
res.end();
}
next()
}