Netlify 15 ๐ Netlify Server & WebSockets โ Deploying persistent Node.js backends (Express, Hono, Fastify) with zero wrappers
Netlify provides a powerful environment for deploying full-stack Node.js applications by abstracting the serverless invocation layer. Traditionally, Node.js frameworks like Express or Fastify are designed to run as long-lived processes listening on a specific port. Netlify Functions allow you to deploy these frameworks by mapping the incoming HTTP request events to the framework’s internal routing engine. This “Lift and Shift” approach enables developers to move existing backend codebases to Netlify without rewriting logic for a serverless event architecture.
While the request-response cycle works seamlessly with this pattern, WebSockets present a unique challenge. Standard Netlify Functions (the serverless compute tier) are ephemeralโthey execute, return a response, and terminate. Because they do not maintain long-lived TCP connections, persistent WebSocket server code cannot run directly within the standard function container. This chapter explores how to deploy Node.js frameworks using adapter patterns and evaluates the architectural requirements for handling real-time features like WebSockets on a serverless infrastructure.
Key point: You can deploy Node.js frameworks like Express or Hono to Netlify by wrapping them in an adapter that translates the platform’s event object into a standard HTTP request; however, standard serverless functions cannot host persistent WebSocket connections, requiring off-platform solutions like managed Pub/Sub or dedicated WebSocket services.
Why exists
The “Lift and Shift” capability.
Many enterprise applications are built on established frameworks like Express or Fastify. Migrating these to a native serverless architecture would require a total rewrite. Adapters allow existing code to run as-is.
The unification of environments.
Developers often prefer to keep their API logic and frontend code in the same repository. Deploying the Node.js backend alongside the frontend on Netlify simplifies CI/CD pipelines and deployment previews.
The serverless compute benefit.
By running Express or Fastify within Netlify Functions, you gain automatic scaling, global distribution, and pay-per-execution billing. You lose the maintenance burden of managing VPS instances or Docker containers.
The abstraction of HTTP events.
Standard Node.js frameworks expect a req and res object tied to a socket. Netlify Functions provide an event object and a context. Adapters bridge this gap, handling the translation so the framework “thinks” it is running on a standard local server.
The reality of real-time requirements.
Modern web apps need real-time data. While you cannot hold a connection open in a function, offloading the connection management to specialized services while keeping the business logic in the framework provides the best of both worlds.
a. The Adapter Pattern
Frameworks like Express and Fastify listen for requests on a network socket. Netlify Functions receive a cloud-provider specific event object. To bridge these, we use an adapter (like serverless-http). The adapter intercepts the request, maps the cloud event to a standard Node http.IncomingMessage and http.ServerResponse, and passes them to your application.
import express from "express";
import serverless from "serverless-http";
const app = express();
app.get("/api/data", (req, res) => {
res.json({ message: "Hello from Express on Netlify" });
});
// The adapter handles the mapping
export const handler = serverless(app);
Once the handler is exported, Netlify invokes it whenever a request matches your configured function path. The application behaves exactly as it would locally, with the frameworkโs router determining which controller handles the incoming request.
b. Deployment and Configuration
Deployment requires mapping specific URL paths to the function entry point using netlify.toml. When the function is triggered, the entire framework is initialized. To optimize performance, global variables and database connections are instantiated outside the handler so they can be reused across warm function invocations.
# netlify.toml
[[functions]]
path = "/api/*"
function = "api-handler"
Because cold starts can add latency, initialization code should be lean. Heavy dependencies like ORMs or connection pools should be initialized lazily or kept in the module scope to benefit from the platform’s execution reuse.
c. The WebSocket Limitation
Netlify Functions are ephemeral and limited by execution duration (typically 10-26 seconds). A WebSocket connection is inherently long-lived and stateful. If you attempt to run a library like socket.io directly inside a Netlify Function, the connection will drop as soon as the function terminates after the request lifecycle.
// โ This will not work on standard Functions
io.on("connection", (socket) => {
// Connection will terminate immediately
});
To support WebSockets, you must decouple the connection handling. The recommended architecture is to use a dedicated WebSocket provider (like Pusher, Ably, or AWS API Gateway) to manage the socket lifecycle, while your Netlify Function handles the REST API or HTTP webhooks that trigger events into those services.
Complete Example Session
// ============================================
// PART 1: THE EXPRESS APPLICATION
// ============================================
import express from "express";
import serverless from "serverless-http";
const app = express();
app.use(express.json());
// ============================================
// PART 2: THE API ROUTE
// ============================================
app.post("/api/submit", (req, res) => {
const { data } = req.body;
// Handle logic...
res.status(200).json({ success: true, received: data });
});
// ============================================
// PART 3: THE ADAPTER
// ============================================
export const handler = serverless(app);
// ============================================
// PART 4: THE CONFIGURATION
// ============================================
// netlify.toml
// [[functions]]
// path = "/api/*"
// function = "server"
This sequence creates an Express application, defines a standard POST route, wraps it in the serverless-http adapter, and configures the netlify.toml to route traffic to the function.
Quick Reference
Supported Framework Adapters
| Framework | Adapter |
|---|---|
| Express | serverless-http |
| Fastify | aws-lambda-fastify |
| Hono | Built-in handle |
| Koa | serverless-http |
WebSocket Alternatives
| Solution | Mechanism |
|---|---|
| Ably / Pusher | Pub/Sub via REST API |
| AWS API Gateway | Managed WebSocket connections |
| Firebase | Realtime Database triggers |
Limitations
| Constraint | Limit |
|---|---|
| Execution Time | Usually 10s – 26s |
| Persistent State | Not supported (Stateless only) |
| Port Binding | Not available |
Best Practices
โ Do This:
// Initialize connections outside the handler
const db = connectToDatabase(); // โ
// Use efficient JSON parsing
app.use(express.json()); // โ
// Define routes clearly
app.get("/api/users", (req, res) => { ... }); // โ
// Offload WebSockets to external services
// fetch("https://api.pusher.com/events", ...); // โ
โ Don’t Do This:
// Initialize database inside the handler
export const handler = async (event) => { const db = connect(); }; // โ
// Use synchronous I/O operations
fs.readFileSync("/file.txt"); // โ
// Try to host Socket.io inside the function
io.listen(3000); // โ
// Store session state in memory variables
let userSession = {}; // โ
Common Pitfalls
| Pitfall | Why It Happens | Fix |
|---|---|---|
| Cold starts | Heavy initialization | Lazy load dependencies |
| State loss | Serverless is stateless | Use external cache (Redis) |
| Timeout | Function execution limit | Offload work to background jobs |
| Socket disconnect | Ephemeral runtime | Use Pub/Sub services |
Real-World Examples
1. Express Adapter
export const handler = serverless(app);
2. Hono Integration
export const handler = handle(app);
3. Database Singleton
const pool = new Pool(); // Global scope
4. JSON Middleware
app.use(express.json());
5. External WebSocket Trigger
await pusher.trigger("my-channel", "event", data);
6. CORS Configuration
app.use(cors());
7. Error Handling
app.use((err, req, res, next) => { res.status(500).send("Error"); });
8. Lazy Loading DB
let cachedDb;
// in handler: cachedDb = cachedDb || await connect();
9. Environment Variables
process.env.DB_URL;
10. Request Object Access
const user = req.headers["x-user"];
Visual
Request Lifecycle (Rest)
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ USER REQUEST โ
โ โ โ
โ โผ โ
โ NETLIFY ADAPTER (serverless-http) โ
โ โ โ
โ โผ (Express/Fastify) โ
โ ROUTER โโโบ CONTROLLER โโโบ DATABASE โ
โ โ โ
โ RESPONSE โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Why WebSockets Fail
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ USER CLIENT โ
โ โ โ
โ โผ โ
โ WS HANDSHAKE โโโบ NETLIFY FUNCTION (Ephemeral) โ
โ โ โ
โ โ [Function Execution Finishes] โ
โ โ โ
โ CONNECTION CLOSED (Function died) โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Recommended Architecture
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ CLIENT โโโโโบ REALTIME SERVICE (Pusher/Ably) โ
โ โฒ โ
โ โ โ
โ NETLIFY FUNCTION โโโโ โ
โ (Triggers event) โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Summary
| Item | Value |
|---|---|
| Core Concept | Adapter Pattern |
| Best Adapter | serverless-http |
| WebSockets | Not supported natively |
| State | Stateless only |
| Optimization | Lazy initialization |
Key takeaways:
- Adapters map events to code. Tools like
serverless-httpallow standard Node.js frameworks to run on serverless platforms without modification. - Functions are ephemeral. Because they do not stay active, you cannot use them to host persistent WebSocket servers like
socket.io. - State must be external. Since the serverless container is destroyed after execution, all session state or persistent data must live in an external database or cache like Redis.
- Architect for real-time. To support WebSockets, use a third-party managed service and trigger updates via API calls from your functions.
- Keep cold starts low. Initialize heavy libraries or database connections in the global scope to reuse them across function invocations.
Remember: Netlify is an excellent place to host your API logic by wrapping your existing Node.js frameworks, but it does not replace a dedicated WebSocket server. Treat your functions as stateless request handlers and offload real-time connection management to specialized infrastructure to ensure scalability and reliability.
Stop using slow, ad-bloated tool sites! ๐คฎ
๐ Search “KandZ Tools” on Google to use many professional utilities for free.
KandZ.me is the ultimate minimalist hub for:
โ
Finance (Mortgage, Interest, Inflation)
โ
Tech (Base64, JSON, Dev Suite, IP)
โ
Health (BMI, BMR, TDEE)
โ
Productivity (Timer, Workspace, QR)
โก๏ธ Fast & Private
๐ No data leaves your device
๐ 100% Free
๐ Use it now: https://tools.kandz.me
๐ Bookmark itโyouโll need it later!