| | |

Netlify 15 ๐ŸŒ Netlify Server & WebSockets โ€” Deploying persistent Node.js backends (Express, Hono, Fastify) with zero wrappers

โฑ๏ธ Estimated read: 7 min | |

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

FrameworkAdapter
Expressserverless-http
Fastifyaws-lambda-fastify
HonoBuilt-in handle
Koaserverless-http

WebSocket Alternatives

SolutionMechanism
Ably / PusherPub/Sub via REST API
AWS API GatewayManaged WebSocket connections
FirebaseRealtime Database triggers

Limitations

ConstraintLimit
Execution TimeUsually 10s – 26s
Persistent StateNot supported (Stateless only)
Port BindingNot 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

PitfallWhy It HappensFix
Cold startsHeavy initializationLazy load dependencies
State lossServerless is statelessUse external cache (Redis)
TimeoutFunction execution limitOffload work to background jobs
Socket disconnectEphemeral runtimeUse 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

ItemValue
Core ConceptAdapter Pattern
Best Adapterserverless-http
WebSocketsNot supported natively
StateStateless only
OptimizationLazy initialization

Key takeaways:

  • Adapters map events to code. Tools like serverless-http allow 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.

Was this helpful?


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!