15

I am using fastify as a web framework in my nodejs project. I want to call all my routes from a directory having a base route defined in main JS file like we do in express. I have read many blogs but i did not find any relevant answer to my question

like in express we assign routes as-

app.use('/user', user_route)

and then in user_route we define all other routes method.

In fastify I have used

fastify.register(require('./routes/users'), { prefix: '/user' })

but then only one function can be called like-

module.exports = function (fastify, opts, done) {
  fastify.get('/user', handler_v1)
  done()
}

What if I want to call multiple route function?

ADITYA HAZARIKA
  • 300
  • 1
  • 4
  • 13

4 Answers4

11

For the base route to work globally in all routes, you can register it in your server.js or app.js whatever you are using to register your server.

 fastify.register(require('../app/routes'), { prefix: 'api/v1' });

Here '../app/routes' points to your directory of routes. All routes that you define will be prefixed by 'api/v1'

Hope this helps.

Antara Datta
  • 1,909
  • 2
  • 12
  • 16
8

You can add many routes to a fastify instance like this:

'use strict'

const Fastify = require('fastify')
const fastify = Fastify({ logger: true })

fastify.register((instance, opts, next) => {

  instance.get('/', (req, res) => { res.send(req.raw.method) })
  instance.post('/', (req, res) => { res.send(req.raw.method) })
  instance.put('/', (req, res) => { res.send(req.raw.method) })
  instance.patch('/', (req, res) => { res.send(req.raw.method) })

  instance.get('/other', (req, res) => { res.send('other code') })

  next()
}, { prefix: 'user' })


fastify.listen(3000, () => {
  console.log(fastify.printRoutes());
})

The .register method is needed only to encapsulate context and plugins. This is useful to split your codebase into smaller files and load only the plugins you need.

In this way you will have a single route that replies different for different HTTP methods: curl -X GET http://localhost:3000/user/ or curl -X PUT http://localhost:3000/user/

Manuel Spigolon
  • 11,003
  • 5
  • 50
  • 73
6

You can use the fastify-autoload plugin

const AutoLoad = require('fastify-autoload')
// define your routes in one of these
fastify.register(AutoLoad, {
    dir: path.join(__dirname, 'services'),
    options: Object.assign({ prefix: '/api' }, opts)
  })
saeid
  • 61
  • 2
4

Fastify supports this even more organized way. I explain this step by step.

  1. Create a directory name like routers
  2. This directory may contain one or multiple .js files. Each file contains one or multiples routes. Like -
async function routes(fastify, options){
    fastify.get('/', async function(request, reply) {
         return {hello: 'world'} 
    }), 

    fastify.get('/bye', async function(request, reply) {
         return {bye: 'good bye'} 
    }) 
}

module.exports = routes

  1. Next register this directory using fastify-autoload. Like
const path = require('path')
const autoload = require('fastify-autoload')

async function app(fastify, options){
    //old standard routing
    //fastify.register(require('./routes/baisc-router'))

    //auto-load, based on directory 
    fastify.register(autoload,{
         dir: path.join(__dirname, 'routes')
    })
}
module.exports = app

For clear details code, you can follow this Git repository.

Md Kawser Habib
  • 1,966
  • 2
  • 10
  • 25