Skip to content

Deprecate re-routing through string parameter to next #1845

@ghermeto

Description

@ghermeto

Today

The current next API for route handlers is the following:

next()

  • goes to the next handler in the chain (if any)

next('fooRoute')

  • re-routes to the route chain that resolves for 'fooRoute'

next(1) (or next({}))

next(new Error('boom'))

  • returns the error (if it has the statusCode property), otherwise converts it into a String and wraps in an InternalServerError (same as passing it a number as the first parameter)

Proposal

Deprecate the API next('fooRoute') and its async/await equivalent. Instead, use an explicit re-routing mechanism similar to what was proposed by @mmarchini:

  server.get('/one', async (req, res, next) => {
    req.routeTo('getTwo');
    next();
  });

  server.get('/two', async (req, res, next) => {
    res.send('two');
    next();
  });
  

The method .routeTo() will set a re-route flag, that will be read after the handler finished and it would re-route at that point without relying on the error chain.

Since setting the flag is synchronous, this approach also works for async functions:

  server.get('/one', async (req, res) => {
    req.routeTo('getTwo');
  });

  server.get('/two', async (req, res) => {
    res.send('two');
  });

This proposal keeps the functionality intact while removing a potential problem for the async/await DevEx.

Thoughts?

cc/ @cprussin

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions