Categories
Node.js Quick Tips Quick Tips

Tips for migrating from Express to Fastify

2 min read

When I was writing the article How to migrate your app from Express to Fastify I noted down a few of the things I learnt along the way.

Server creation and configuration is quite similar

Changing the creation and configuration of an Express server instance over to Fastify requires a fairly small set of changes:

diff --git a/api-after/package.json b/api-after/package.json
index 8efee6f..f51a9c8 100644
--- a/api-after/package.json
+++ b/api-after/package.json
@@ -11,6 +11,9 @@
   "license": "MIT",
   "dependencies": {
     "cors": "^2.8.5",
-    "express": "^4.17.1"
+    "express": "^4.17.1",
+    "fastify": "^3.13.0",
+    "fastify-express": "^0.3.2"
   }
 }
diff --git a/api-after/src/server.js b/api-after/src/server.js
index 22a692e..156553e 100644
--- a/api-after/src/server.js
+++ b/api-after/src/server.js
@@ -1,14 +1,17 @@
 // src/server.js
 
-import express from "express";
+import Fastify from "fastify";
+import ExpressPlugin from "fastify-express";
 
 import config from "./config.js";
 import routes from "./routes.js";
 
-const app = express();
+const fastify = Fastify({
+       logger: true
+});
 
-app.use("/user", routes);
+await fastify.register(ExpressPlugin);
 
-const server = app.listen(3000, () => {
-       console.log(\`Example app listening at http://localhost:${server.address().port}\`);
-});
+fastify.use("/user", routes);
+
+fastify.listen(3000);

Fastify plugins are configured a little differently to Express middleware

In Express you typically configure middleware by calling it with an options object e.g.

cors({ origin: true });

With Fastify plugins you don’t call them, but you pass in options separately instead e.g.

fastify.register(CorsPlugin, { origin: true });
Screenshot of code showing the difference between how you configure an Express middleware and how you configure a Fastify plugin

Express routes won’t show up when you call fastify.printRoutes()

If you’re using the use() method from fastify-express to add Express routes, they won’t show up when you call fastify.printRoutes().

My understanding is that this is because they’re not registered as "real" routes in Fastify’s router.

Documentation: https://www.fastify.io/docs/latest/Server/#printroutes

Fastify automatically serializes objects and arrays to JSON when you send them

When you migrate Express routes to Fastify routes, change calls to response.json() to reply.send().

There is no reply.json() method in Fastify as reply.send() serializes objects and arrays to JSON automatically.

Documentation: https://www.fastify.io/docs/latest/Reply/#senddata

Screenshot of code showing the difference between how you send an object as JSON in Express vs Fastify