Skip to content

Instantly share code, notes, and snippets.

@renoirb
Last active June 28, 2022 23:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save renoirb/e201ee73e78ac80e1b7d1bc6dfec6c6f to your computer and use it in GitHub Desktop.
Save renoirb/e201ee73e78ac80e1b7d1bc6dfec6c6f to your computer and use it in GitHub Desktop.
Nuxt 'render:setupMiddleware' hook example
// file: hooks/index.js
import render from './render'
// 'render:context'
export default (nuxtConfig) => ({
render: render(nuxtConfig),
})
// 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 {
/**
* 'render:setupMiddleware'
* {@link node_modules/nuxt/lib/core/renderer.js}
*/
setupMiddleware(app) {
app.use('/', redirectRootToPortal(base))
},
}
}
// file: hooks/route-redirect-portal.js
/**
* Nuxt middleware hook to redirect from / to /portal (or whatever we set in nuxt.config.js router.base)
*
* Should be the same version as connect
* {@link node_modules/connect/package.json}
*/
import parseurl from 'parseurl'
/**
* Connect middleware to handle redirecting to desired Web Applicatin Context Root.
*
* Notice that Nuxt docs lacks explaning how to use hooks.
* This is a sample router to help explain.
*
* See nice implementation for inspiration:
* - https://github.com/nuxt/nuxt.js/blob/dev/examples/with-cookies/plugins/cookies.js
* - https://github.com/yyx990803/launch-editor/blob/master/packages/launch-editor-middleware/index.js
*
* [http_class_http_clientrequest]: https://nodejs.org/api/http.html#http_class_http_clientrequest
* [http_class_http_serverresponse]: https://nodejs.org/api/http.html#http_class_http_serverresponse
*
* @param {http.ClientRequest} req Node.js internal client request object [http_class_http_clientrequest]
* @param {http.ServerResponse} res Node.js internal response [http_class_http_serverresponse]
* @param {Function} next middleware callback
*/
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) {
console.log('routeRedirectPortalHandler', {
desiredContextRoot,
startsWithDesired,
isNotProperContextRoot,
url,
})
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()
}
// file: nuxt.config.js
import hooks from './hooks'
// Typical nuxt.config.js, plus...
export default {
router: {
base: '/portal',
},
hooks: hooks(this),
}
@renoirb
Copy link
Author

renoirb commented Nov 15, 2018

Related to nuxt/docs#984, and cmty.app #c142


Issue description (copy)

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.

@FuriosoJack
Copy link

FuriosoJack commented Nov 1, 2021

Fatal error,

FATAL  Reflect.has called on non-object                                                                                                                                                                                      10:52:00

  at Object.has (<anonymous>)
  at _default (hooks/render.js:6:26)
  at _default (hooks/index.js:5:31)
  at nuxt.config.js:89:29
  at g (node_modules/jiti/dist/jiti.js:1:55111)
  at Object.loadNuxtConfig (node_modules/@nuxt/config/dist/config.js:1082:15)
  at loadNuxtConfig (node_modules/@nuxt/cli/dist/cli-index.js:338:32)
  at NuxtCommand.getNuxtConfig (node_modules/@nuxt/cli/dist/cli-index.js:463:26)
  at Object.run (node_modules/@nuxt/cli/dist/cli-build.js:90:30)
  at NuxtCommand.run (node_modules/@nuxt/cli/dist/cli-index.js:413:22)

@renoirb
Copy link
Author

renoirb commented Nov 1, 2021

Fatal error,

FATAL  Reflect.has called on non-object                                                                                                                                                                                      10:52:00

This Gist is dating back from 2018. What version of Nuxt are you using? API Must've changed in 35 months.

Tip from a mentor of mine.

Code on the Interweb should be seen as "Chewing Gum" you find on the street. Don't pick and chew and expect it'll work :)
You'll have to figure out what changed and go through the steps I've been through at that time. The docs I've contributed isn't there anymore.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment