Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for nested routes #14

Merged
merged 1 commit into from
Feb 13, 2024
Merged

Conversation

paulrobertlloyd
Copy link
Contributor

@paulrobertlloyd paulrobertlloyd commented Feb 13, 2024

With express.Router, it’s possible to create self-contained routing beneath a path set in a parent router. Using an example slightly modified from the Express JS documentation:

// birds.js
import express from 'express'

const router = express.Router()

router.get('/', (req, res) => {
  res.send('Birds home page')
})

router.get('/about', (req, res) => {
  res.send('About birds')
})

export const birdRoutes = router
// routes.js
import { birdRoutes } from 'birds.js'

app.use('/birds', birdRoutes)

The app will now be able to handle requests to /birds and /birds/about.

However, while this library looks for paths that match req.originalUrl, it only creates next and previous paths based on the route handler. For example, given the following journey:

const journey = {
  '/': {},
  '/about': {}
  '/species': {}
}

Upon visiting /about, the following paths object is provided:

{
  back: '/',
  current: '/birds/about',
  next: '/species'
}

Note that back and next values don’t contain the parent path segment. Clicking on links containing those values will return the wrong (or no) page.


This PR appends req.baseUrl which includes this information. With this fix in place, the following paths are generated:

{
  back: '/birds',
  current: '/birds/about',
  next: '/birds/species'
}

If there is no req.baseUrl, the previous behaviour is retained.

@paulrobertlloyd paulrobertlloyd merged commit 86a6304 into main Feb 13, 2024
1 check passed
@paulrobertlloyd paulrobertlloyd deleted the support-nested-routes branch February 13, 2024 11:09
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant