PostCSS Middleware for Express/Connect
raw JSON →This package provides a middleware function to integrate PostCSS processing into web servers built with Connect or Express. It enables on-the-fly compilation of CSS files using a configurable array of PostCSS plugins, allowing developers to leverage modern CSS features and optimizations directly within their server setup. The current stable version is 1.1.4. While its core functionality remains robust, the project appears to be in a maintenance state with infrequent updates, with the last commit dating back over two years. Its primary differentiator is its direct integration as a server-side middleware, offering dynamic CSS processing without requiring a separate build step during development, which can be useful for rapid prototyping or specific server-rendered scenarios. It requires PostCSS plugins to be explicitly passed as an array, offering full flexibility in defining the CSS processing pipeline.
Common errors
error TypeError: Cannot read properties of undefined (reading 'length') ↓
plugins array is provided and contains at least one PostCSS plugin instance, e.g., plugins: [require('autoprefixer')]. error Error: ENOENT: no such file or directory, stat '/path/to/your/app/undefined' ↓
src function. Add console.log('Requested URL:', req.url, 'Resolved Path:', filePath); inside your src function to verify the path being generated matches an existing file on disk. error ReferenceError: autoprefixer is not defined ↓
npm install <plugin-name> (e.g., npm install autoprefixer). Ensure the plugin is correctly imported/required where postcssMiddleware is configured. Warnings
gotcha The middleware bundles PostCSS v5.x as a direct dependency. While it may load newer PostCSS plugins, significant changes in PostCSS's plugin API between v5 and v8 could lead to unexpected behavior or errors if your plugins require newer PostCSS versions. ↓
gotcha Dynamic PostCSS processing on every request can be a significant performance bottleneck in production environments. The middleware processes CSS files synchronously (or near-synchronously) for each request, which is inefficient for high-traffic applications. ↓
gotcha The `src` option requires careful configuration to correctly resolve file paths based on the incoming request URL. Incorrectly configured `src` functions can lead to 404 errors or serving the wrong CSS files, especially with complex routing or file structures. ↓
Install
npm install postcss-middleware yarn add postcss-middleware pnpm add postcss-middleware Imports
- postcssMiddleware wrong
import postcssMiddleware from 'postcss-middleware';correctconst postcssMiddleware = require('postcss-middleware'); - postcssMiddleware wrong
import postcssMiddleware from 'postcss-middleware';correctimport * as postcssMiddleware from 'postcss-middleware';
Quickstart
import express from 'express';
import * as postcssMiddleware from 'postcss-middleware';
import autoprefixer from 'autoprefixer';
import path from 'path';
// Ensure you have a 'public/styles' directory with 'app.css'
// Example content for public/styles/app.css:
/*
body {
display: flex;
color: blue;
}
*/
const app = express();
const port = 3000;
// Serve static files from the 'public' directory
app.use(express.static(path.join(__dirname, 'public')));
app.use('/css', postcssMiddleware({
plugins: [
autoprefixer({
overrideBrowserslist: ['last 2 versions', '> 1%']
})
],
src: function(req) {
// Resolve the CSS file path relative to the 'public/styles' directory
// For a request like /css/app.css, it will look for public/styles/app.css
const filePath = path.join(__dirname, 'public', 'styles', req.path.replace('/css/', ''));
console.log(`[postcss-middleware] Request for ${req.url}, resolving to ${filePath}`);
return filePath;
},
options: {
map: { inline: true } // Generate inline sourcemaps for debugging in browsers
}
}));
app.get('/', (req, res) => {
res.send(`
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>PostCSS Middleware Example</title>
<link rel="stylesheet" href="/css/app.css">
</head>
<body>
<h1>Hello from Express with PostCSS!</h1>
<p>This paragraph should be styled with Autoprefixer if you inspect its computed styles.</p>
<p>Check the network tab for 'app.css' and its source map.</p>
</body>
</html>
`);
});
app.listen(port, () => {
console.log(`Server listening on http://localhost:${port}`);
console.log('Access the example at http://localhost:3000');
});