DEV Community

Cover image for Create a Fastify server
Thomas Bnt ☕
Thomas Bnt ☕ Subscriber

Posted on • Updated on

Create a Fastify server

Introduction

Fastify is a web server framework like ExpressJS but with better performances.

Benchmark on the website Fastify.io

The ecosystem is pretty cool, he adds multiple plugins. But in this first test, I only add fastify-static for getting .html files.

Let's code !

At the first time, create a void folder and install Fastify and fastify-static.

npm i fastify fastify-static
Enter fullscreen mode Exit fullscreen mode

Create an app.js, it's your root file.

Into the app.js

You can write the basis of this file for creating a new Fastify server.

const path = require("path")
const f = require('fastify')({logger: false})

f.register(require('fastify-static'), {
    root: path.join(__dirname, 'public'),
    prefix: '/public/',
})

// In this example, when you get localhost:3000, ou have the time
f.get('/', (request, reply) => {
    reply.header('Content-Type', 'application/json')
    reply.send({hello: new Date()})
})
f.get('/about', (request, reply) => {
    reply.sendFile('about.html' )
})


const start = async () => {
    try {
        await f.listen(3000)
    } catch (err) {
        f.log.error(err)
        process.exit(1)
    }
}
start().then(r => r)
Enter fullscreen mode Exit fullscreen mode

Public HTML pages

Create a /public folder and a about.html file.

Create your public folder

End

It's a very short post, but I demonstrate how to simply start a server with Fastify. As this is the first time I use it, there might be some errors. Don't hesitate to give me feedback in the comments ! 👍🏼

Getting Started with Fastify


Check my Twitter account. You can see many projects and updates. You can also support me on Buy Me a Coffee, Stripe or GitHub Sponsors. Thanks for read my post ! 🤩

Top comments (0)