Connect HTTP Middleware Framework
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
-
TypeError: app.use is not a function
cause `connect()` was not called to create the application instance, or `app` is not the result of `connect()`.fixEnsure you are initializing your application correctly: `const connect = require('connect'); const app = connect();` -
Error: Cannot find module 'body-parser'
cause A middleware (e.g., `body-parser`, `compression`, `cookie-session`) is used without being explicitly installed and required. Connect v3.x externalized most middleware.fixInstall the missing middleware via npm (e.g., `npm install body-parser`) and then `require()` it in your application code. -
Error: Can't set headers after they are sent.
cause This common HTTP error occurs when a response is attempted to be sent or modified after `res.end()`, `res.send()`, or `res.json()` has already been called in a preceding middleware or the current one.fixReview your middleware chain. Ensure that only one middleware sends the final response or that `next()` is not called after `res.end()`. Place `next(error)` calls appropriately for error handling.
Warnings
- breaking Connect v3.x removed many previously bundled middleware, requiring developers to install them as separate npm packages. This includes `bodyParser`, `json`, `urlencoded` (now `body-parser`), `compress` (now `compression`), `timeout` (now `connect-timeout`), `cookieParser` (now `cookie-parser`), `limit`, and `multipart`.
- breaking Connect v3.x dropped support for Node.js versions prior to 0.10.x. Newer Node.js features may not be fully leveraged or supported in this older framework version.
- deprecated The `basic-auth` middleware was deprecated in Connect v3.x. While not removed, new development or bug reports are no longer accepted for it.
- gotcha As a framework focused on minimalism, Connect does not inherently include protections against all web vulnerabilities. Middleware used with Connect, especially older or unmaintained ones, may introduce security risks such as XSS or ReDoS if not carefully chosen and configured.
Install
-
npm install connect -
yarn add connect -
pnpm add connect
Imports
- connect
import connect from 'connect';
const connect = require('connect'); - app.use
app.use(function(req, res, next) { /* ... */ next(); }); - error middleware
app.use(function(err, req, res, next) { /* handle error */ });
Quickstart
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}`);
});