DEV Community

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

Posted on • Edited on

24 8

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 ! 🤩

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay