Connect HTTP Middleware Framework

3.7.0 · maintenance · verified Sun Apr 19

Connect is a minimalist, high-performance HTTP server framework for Node.js, built around the concept of 'middleware' plugins. It provides a simple, extensible mechanism to compose request handling functions into a stack, where each middleware can process the request, modify the response, and then pass control to the next middleware or end the request-response cycle. This architecture makes Connect a foundational component for more feature-rich frameworks like Express.js. The package's current stable version is 3.7.0, last published in May 2019, indicating a mature and stable project that is now in a maintenance phase rather than active feature development. Connect differentiates itself by being extremely lightweight, offering only core middleware functionality, and relying on the ecosystem for specific tasks like body parsing or session management, which were largely externalized starting from version 3.0.0.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates setting up a basic Connect application with common external middleware (compression, cookie-session, body parsing) and illustrating basic routing and error handling before starting an HTTP server.

const connect = require('connect');
const http = require('http');
const compression = require('compression');
const cookieSession = require('cookie-session');
const bodyParser = require('body-parser');

const app = connect();

// Gzip/deflate outgoing responses
app.use(compression());

// Store session state in browser cookie
// Note: `keys` should be strong, randomly generated strings in production.
app.use(cookieSession({
  keys: ['super-secret-key-1', 'super-secret-key-2']
}));

// Parse urlencoded request bodies into req.body
app.use(bodyParser.urlencoded({ extended: false }));

// Example middleware that logs the request method and URL
app.use(function logRequest(req, res, next) {
  console.log(`${req.method} ${req.url}`);
  next();
});

// Respond to a specific path
app.use('/hello', function(req, res) {
  res.setHeader('Content-Type', 'text/plain');
  res.end('Hello from Connect on /hello!\n');
});

// General fallback response for all other requests
app.use(function(req, res) {
  res.setHeader('Content-Type', 'text/plain');
  res.end('Hello from Connect! Try /hello\n');
});

// Error handling middleware (must take 4 arguments)
app.use(function onError(err, req, res, next) {
  console.error(err.stack);
  res.statusCode = 500;
  res.end('Something broke!\n');
});

// Create node.js http server and listen on port
const PORT = process.env.PORT || 3000;
http.createServer(app).listen(PORT, () => {
  console.log(`Connect server listening on port ${PORT}`);
  console.log(`Access at http://localhost:${PORT}`);
});

view raw JSON →