High performance Node.js static file serving — using Rust

High performance Node.js static file serving — using Rust


A few months ago we released Encore.ts — an Open Source backend framework for TypeScript / Node.js.

Since there are already many frameworks out there, we want to share some of the outlier design decisions we’ve made and how they lead to improved performance and developer experience.



Serving static files in Node.js, using Rust for high performance

Encore.ts comes with built-in support for serving static assets (such as images, HTML and CSS files, and JavaScript files).

This is useful when you want to serve a static website or a single-page application (SPA) that has been pre-compiled into static files.

When defining static files, the files are served directly from the Encore.ts Rust Runtime.

This means that no JavaScript code is executed to serve the files, freeing up the Node.js runtime to focus on executing business logic.

This dramatically speeds up both the static file serving, as well as improving the latency of your API endpoints.

We recently published benchmarks showing how it is 9x faster than Express.js based Node applications.

Learn more in the docs

Example app showing how to serve static files with Encore.ts



Code example

Serving static files in Encore.ts works similar to have you define API endpoints, but using the api.static function instead of the normal api function.

import { api } from "encore.dev/api";

export const assets = api.static(
  { expose: true, path: "/frontend/*path", dir: "./assets" },
);
Enter fullscreen mode

Exit fullscreen mode

This will serve all files in the ./assets directory under the /frontend path prefix.

Encore automatically serves index.html files at the root of a directory. In the case above, that means that requesting the URL /frontend will serve the file ./assets/index.html, and /frontend/hello will serve the file ./assets/hello or ./assets/hello/index.html (whichever exists).



Wrapping up

By using a Rust based runtime alongside Node.js, Encore.ts is able to improve performance of TypeScript applications.

If performance matters to your project, it might be a good idea to try out Encore.ts.

And it’s all Open Source, so you can check out the code and contribute on GitHub.



Source link
lol

By stp2y

Leave a Reply

Your email address will not be published. Required fields are marked *

No widgets found. Go to Widget page and add the widget in Offcanvas Sidebar Widget Area.