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

Use-case: When router.base is not default, when going to /, instead of 404, redirect to router.base as a Nuxt connect middleware example #984

@renoirb

Description

@renoirb

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.

  1. Setup Nuxt config

    // file: nuxt.config.js
    import hooks from './hooks'
    export default {
      router: {
        base: '/portal',
      },
      hooks: hooks(this),
    }
  2. Hooks module setup

    // file: hooks/index.js
    import render from './render'
    export default (nuxtConfig) => ({
      // e.g. 'render:context'
      render: render(nuxtConfig),
    })
  3. 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))
        },
      },
    }
  4. 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()
    }

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions