Skip to content

Nested router's middleware has no access to request params #122

Open
@egorovli

Description

@egorovli

node.js version: 16.2.0
yarn version: 1.22.10
@koa/router version: 10.0.0
koa version: 2.13.1

Code sample:

let usersRouter = new Router()
  .use(async (ctx, next) => {
    console.log(ctx.params.userId ?? 'No user ID in params')
    return next()
  })
  .get('/', async (ctx, next) => {
    ctx.body = {
      id: 1,
      name: 'John Doe'
    }
  })

export let router = new Router()
  .use('/users/:userId', usersRouter.routes(), usersRouter.allowedMethods())

Expected Behavior:

The middleware prints userId to console.

Actual Behavior:

The middleware prints 'No user ID in params' because ctx.params.userId is undefined.

Additional steps, HTTP request details, or to reproduce the behavior or a test case:

This is actually fixed by calling .use() with an empty path 🤷‍♂

let usersRouter = new Router()
  // Here an empty path is used. Previosly it was omitted.
  .use('', async (ctx, next) => {
    console.log(ctx.params.userId ?? 'No user ID in params')
    return next()
  })
  .get('/', async (ctx, next) => {
    ctx.body = {
      id: 1,
      name: 'John Doe'
    }
  })

export let router = new Router()
  .use('/users/:userId', usersRouter.routes(), usersRouter.allowedMethods())

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions