Skip to content
This repository has been archived by the owner on May 23, 2022. It is now read-only.

Routes & Routers

Logan Shaw edited this page Oct 4, 2021 · 6 revisions

Creating Routes

To start, create a new typescript file in ./src/routes. For this example we will be using myRouter.ts.

Then import the Router function from express and initialize the router:

  import { Router } from 'express'

  const MyRouter = Router()

Exporting Routes

Now we can choose to export this router in two ways:

  1. Use DRL w/ object metadata
  2. Export without DRL

Note: DRL stands for "Dynamic Route Loading"


DRL w/ object metadata (Recommended)

First we'll start off with the two more standard methods using DRL.

To export with metadata you simply define a property on MyRouter, and export it as default:

  const MyRouter = server.router("/myRouter")

  export default MyRouter

This will hook the router you created to /myRouter.

Note: Routers can be exported as router rather than default:

  export const router = MyRouter

Export without DRL

Alternatively you can export directly to ./src/index.ts without using DRL.

Note: This method is not recommended and is here purely for reference. You will most likely be asked to change to using DRL if you submit a pull request with it.

./src/routes/myRouter.ts:

  const MyRouter = Router()

  export default MyRouter

./src/routes/index.ts:

  import MyRouter from './myRouter'

  export {
    MyRouter
  }

./src/index.ts:

  import {
    MyRouter
  } from './routes/index'

  ...

  app.use("/myRouter", MyRouter)
Clone this wiki locally