View profile

Write Your Own Express.js From Scratch

Write Your Own Express.js From Scratch
By Mastering JS Weekly • Issue #42 • View online
Last week we shipped our first premium tutorial: Write Your Own Express.js From Scratch, now available on our Gumroad. We believe that the best way to truly master a framework is to try to write it yourself. Writing a clone will teach you more about the framework’s concepts and limitations than years of combing through the documentation.
Write Your Own Express.js From Scratch is a 4-step tutorial explaining how to write a minimal clone of Express called Espresso. It focuses primarily on routing and middleware, which are the fundamental building blocks of Express.

Everything is Middleware
If you needed to explain Express in one sentence, it would look something like this: an Express app is an array of middleware functions that Express executes in sequence on every inbound HTTP request. Express functions like `app.use()`, `app.get()`, and `` push a new layer (an object wrapper about a middleware function) onto the middleware’s list of layers.
For example, suppose you want to write an `Espresso` class that works just like Express for the below script:
Looks like Express
Looks like Express
Your Espresso class needs to implement two methods: `use()` and `listen()`. The `use()` function adds a new middleware to the middleware stack, and `listen()` tells the server to listen on a given port.
Implementing `use()` and `listen()`
Implementing `use()` and `listen()`
So `use()` is simple: it just pushes a function onto the stack. This is similar to what `Router.use()` does in Express.
The `listen()` function creates a new HTTP server that uses Espresso’s `handle()` function. This is also similar to how Express’ `listen()` function works. Each time a new request comes in, Espresso calls `this.handle()`.
The `this.handle()` function is where the work of handling the request happens. This function calls each middleware in `_stack` in series with `req`, `res`, and a custom function `next()` that kicks off the next middleware in `_stack`.
How `handle()` works
How `handle()` works
Route handlers (the callbacks for `app.get()`, ``, etc.) are just middleware that does not call `next()`. If a middleware function doesn’t call `next()`, then Express will never call the subsequent middleware, which can be the right choice if that middleware function sends an HTTP response.
Routers, like `express.Router()`, are also middleware functions. They just happen to be middleware functions that have their own middleware stack.
Want to learn more? Get the tutorial and become an Express expert today!
Recent Tutorials
Recommended Reading
Functional Design Patterns for Express.js
Did you enjoy this issue?
Mastering JS Weekly

A weekly summary of our tutorials

If you don't want these updates anymore, please unsubscribe here.
If you were forwarded this newsletter and you like it, you can subscribe here.
Powered by Revue