Registry / web-framework / postcss-middleware

postcss-middleware

JSON →
library1.1.4jsnpmunverified

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.

npm install postcss-middleware
INSTALL
IMPORT
SIG · POSTCSS-MIDDLEWARE
P
postcss-middleware
web-frameworkjavascriptv1.1.4
Install
—
Import
—
Disk
—
Pass rate
0/ 6
Env Coverage0 / 6
glibc
18–22
musl
18–22
Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
node 18–226 runs
build_error
glibc
node 18–226 runs
build_error
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

postcssMiddleware
✓ const postcssMiddleware = require('postcss-middleware');
✗ import postcssMiddleware from 'postcss-middleware';
This package is a CommonJS module. Direct `import` syntax without `* as` or `esModuleInterop` may lead to issues in pure ESM environments or strict TypeScript configurations.
postcssMiddleware
✓ import * as postcssMiddleware from 'postcss-middleware';
✗ import postcssMiddleware from 'postcss-middleware';
For TypeScript, `import * as` is the recommended way to import CommonJS modules to correctly capture all exports, including the default function.

This example sets up an Express server that uses `postcss-middleware` to dynamically process CSS files with Autoprefixer. It demonstrates basic server setup, middleware configuration, and a simple HTML page linking to the processed CSS. It expects a CSS file in `public/styles/app.css` to be processed and served on demand.

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'); });
Debug
Known issues
gotchaThe 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.
fix
Check the `peerDependencies` or documentation of your PostCSS plugins for their required PostCSS version. If incompatible, consider alternatives that are actively maintained with newer PostCSS versions, or use older versions of PostCSS plugins compatible with PostCSS v5.x.
affects: >=1.0.0
gotchaDynamic 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.
fix
For production, pre-compile your CSS using a dedicated build tool (e.g., Webpack, Rollup, Gulp, standalone PostCSS CLI) and serve static CSS files. Only use `postcss-middleware` for development to avoid build steps during local development.
affects: >=1.0.0
gotchaThe `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.
fix
Always use `path.join` for constructing file paths to ensure platform compatibility. Thoroughly test your `src` function with various request URLs and file structures to confirm it resolves to the expected source files. Log `req.url` and the constructed path during development.
affects: >=1.0.0
Errors
Common errors & fixes
TypeError: Cannot read properties of undefined (reading 'length')
The `plugins` option is missing or an empty array, which is a required parameter for the middleware.
fix
Ensure the `plugins` array is provided and contains at least one PostCSS plugin instance, e.g., `plugins: [require('autoprefixer')]`.
Error: ENOENT: no such file or directory, stat '/path/to/your/app/undefined'
The `src` function is not returning a valid file path, or the file does not exist at the resolved path. The middleware cannot find the source CSS file.
fix
Debug your `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.
ReferenceError: autoprefixer is not defined
A PostCSS plugin (e.g., `autoprefixer`) used in the `plugins` array has not been installed via npm, or it's not correctly imported/required.
fix
Install the missing PostCSS plugin(s) using `npm install <plugin-name>` (e.g., `npm install autoprefixer`). Ensure the plugin is correctly imported/required where `postcssMiddleware` is configured.
Upgrade
Version history
1.1.4latest on npm
Audit
Dependencies
postcssrequiredCore PostCSS library required to process CSS files using the provided plugins, explicitly listed as a direct dependency.
Agent activity
2 hits · last 30 days
node
2
Resources
postcss-middleware — npm install postcss-middleware · libregistry