DEV Community

Cover image for Fastify vs Express
NaseerHines
NaseerHines

Posted on

Fastify vs Express

Okay so as a developer I love trying out new stuff when I was diving into other types of middleware I came across this framework called fastify. I mostly use express so this is me comparing the two in my own opinion. So when developing your server thinking about what middleware you are going to use is rather important. They are lots of factors that can come into play when deciding and choosing a middleware that can specialize in the kind of support your server needs is always first in my opinion. If you are interested in trying out a new middleware fastify can get the job done. Fastify is a web framework highly focused on providing the best developer experience with the least overhead and a powerful plugin architecture. It has three core focuses when it comes to showcasing it to its users. It is highly performant, extendible, and very developer-friendly. It also goes Hand in Hand with NodeJS
When I say highly performant I'm primarily talking speeds as it is said to have 20% faster request than the norm express most people developers use.

To add fastify to your project you need to npm install it with the following line.

npm install fastify

Implementation demo
In your server/index.js or whatever you name it

// Require the framework and instantiate it
const fastify = require('fastify')({ logger: true })

// Declare a route
fastify.get('/', async (request, reply) => {
  return { hello: 'world' }
})

// Run the server!
const start = async () => {
  try {
    await fastify.listen(3000)
    fastify.log.info(`server listening on ${fastify.server.address().port}`)
  } catch (err) {
    fastify.log.error(err)
    process.exit(1)
  }
}
start()

Here is how I would do it if I were using express

const express = require('express')
const app = express()
const port = 3000

app.get('/', (req, res) => res.send('Hello World!'))

app.listen(port, () => console.log(`Example app listening at http://localhost:${port}`))

Another great quality of fastify I wish I had looked into is that it works really well typescript. I say this because the project I'm currently working on is using typescript and we decided to use typescript on both the back-end and the front-end so bringing in a middleware that was more friendly to the language would have been great. Especially since sequelize was already proving to be a headache with the language. If we wanted to start an HTTP server using typescript it would look something like this

import * as fastify from 'fastify'
import { Server, IncomingMessage, ServerResponse } from 'http'

const server: fastify.FastifyInstance = fastify({})

const opts: fastify.RouteShorthandOptions = {
  schema: {
    response: {
      200: {
        type: 'object',
        properties: {
          pong: {
            type: 'string'
          }
        }
      }
    }
  }
}

server.get('/ping', opts, async (request, reply) => {
  return { pong: 'it worked!' }
})

server.listen(3000, (err) => {
  if (err) {
    server.log.error(err)
    process.exit(1)
  }
  server.log.info(`server listening on ${server.server.address().port}`)
})

Then you can just simply run your server with node or however you want to do the process.

In the end, there are obviously lots of different kinds of middleware out there and they can handle different cases. Express being sort of the norm in my opinion it will always have a stacked community behind it. Fastifyu has the community and in some ways is better than express. Choosing the right one depends on what your app does hand how your team chooses to meet those standards.

Top comments (4)

Collapse
 
g33knoob profile image
G33kNoob • Edited

i use fastify with 'joi-hapi' schema validator, its really fun to use fastify and maybe i can say fastify is same as express because you can natively writing express on fastify, but if you want to get 'diffirent experience, try use loopback or maybe sails

Collapse
 
calvintwr profile image
calvintwr

Great article thanks. Do you know in terms of the ecosystem of Fastify, is it comparable to express? Iā€™m thinking of switching over as well but there are a lot of express or express-centric middlewares that are pretty good. And a lot of documentations also.

Collapse
 
hood profile image
Andrea Cappuccio

Just wanted to chimen in and suggest you try out NestJS. If you're ok with TypeScript it's really a totally different level.

Collapse
 
nirnejak profile image
Jitendra Nirnejak

Nice article, gives a direct and clear comparison of both micro frameworks. I will also recommend reading this if you want a bit more technical details on both the frameworks - Express.js vs Fastify - In-Depth Comparison of Node.js Frameworks