API: The hooks Property

  • Type: Object

Hooks are listeners to Nuxt events that are typically used in Nuxt modules, but are also available in nuxt.config.js. Learn More

Example (nuxt.config.js):

  1. import fs from 'fs'
  2. import path from 'path'
  3. export default {
  4. hooks: {
  5. build: {
  6. done (builder) {
  7. const extraFilePath = path.join(builder.nuxt.options.buildDir, 'extra-file')
  8. fs.writeFileSync(extraFilePath, 'Something extra')
  9. }
  10. }
  11. }
  12. }

Internally, hooks follow a naming pattern using colons (e.g., build:done). For ease of configuration, you can structure them as an hierarchical object when using nuxt.config.js (as exemplifed above) to set your own hooks. See Nuxt Internals for more detailed information on how they work.

List of hooks

Examples

Redirect to router.base when not on root

Let´s say you want to serve pages as /portal instead of /.

This is maybe an edge-case, and the point of nuxt.config.jsrouter.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.In order to prevent this, you can setup a Hook.

Maybe redirecting is not the best use-case for a production Web site, but this will help you leverage Hooks.

To begin, you can change router.base; Update your nuxt.config.js:

  1. // nuxt.config.js
  2. import hooks from './hooks'
  3. export default {
  4. router: {
  5. base: '/portal'
  6. }
  7. hooks: hooks(this)
  8. }

Then, create a few files;

  • hooks/index.js, Hooks module
  1. // file: hooks/index.js
  2. import render from './render'
  3. export default nuxtConfig => ({
  4. render: render(nuxtConfig)
  5. })
  • hooks/render.js, Render hook
  1. // file: hooks/render.js
  2. import redirectRootToPortal from './route-redirect-portal'
  3. export default (nuxtConfig) => {
  4. const router = Reflect.has(nuxtConfig, 'router') ? nuxtConfig.router : {}
  5. const base = Reflect.has(router, 'base') ? router.base : '/portal'
  6. return {
  7. /**
  8. * 'render:setupMiddleware'
  9. * {@link node_modules/nuxt/lib/core/renderer.js}
  10. */
  11. setupMiddleware (app) {
  12. app.use('/', redirectRootToPortal(base))
  13. }
  14. }
  15. }
  • hooks/route-redirect-portal.js, The Middleware itself
  1. // file: hooks/route-redirect-portal.js
  2. /**
  3. * Nuxt middleware hook to redirect from / to /portal (or whatever we set in nuxt.config.js router.base)
  4. *
  5. * Should be the same version as connect
  6. * {@link node_modules/connect/package.json}
  7. */
  8. import parseurl from 'parseurl'
  9. /**
  10. * Connect middleware to handle redirecting to desired Web Applicatin Context Root.
  11. *
  12. * Notice that Nuxt docs lacks explaning how to use hooks.
  13. * This is a sample router to help explain.
  14. *
  15. * See nice implementation for inspiration:
  16. * - https://github.com/nuxt/nuxt.js/blob/dev/examples/with-cookies/plugins/cookies.js
  17. * - https://github.com/yyx990803/launch-editor/blob/master/packages/launch-editor-middleware/index.js
  18. *
  19. * [http_class_http_clientrequest]: https://nodejs.org/api/http.html#http_class_http_clientrequest
  20. * [http_class_http_serverresponse]: https://nodejs.org/api/http.html#http_class_http_serverresponse
  21. *
  22. * @param {http.ClientRequest} req Node.js internal client request object [http_class_http_clientrequest]
  23. * @param {http.ServerResponse} res Node.js internal response [http_class_http_serverresponse]
  24. * @param {Function} next middleware callback
  25. */
  26. export default desiredContextRoot =>
  27. function projectHooksRouteRedirectPortal (req, res, next) {
  28. const desiredContextRootRegExp = new RegExp(`^${desiredContextRoot}`)
  29. const _parsedUrl = Reflect.has(req, '_parsedUrl') ? req._parsedUrl : null
  30. const url = _parsedUrl !== null ? _parsedUrl : parseurl(req)
  31. const startsWithDesired = desiredContextRootRegExp.test(url.pathname)
  32. const isNotProperContextRoot = desiredContextRoot !== url.pathname
  33. if (isNotProperContextRoot && startsWithDesired === false) {
  34. const pathname = url.pathname === null ? '' : url.pathname
  35. const search = url.search === null ? '' : url.search
  36. const Location = desiredContextRoot + pathname + search
  37. res.writeHead(302, {
  38. Location
  39. })
  40. res.end()
  41. }
  42. next()
  43. }

Then, whenever a colleague in development accidentally hits / to reach the development web development service, Nuxt will automatically redirect to /portal