PostCSS Middleware for Express/Connect

raw JSON →
1.1.4 verified Thu Apr 23 auth: no javascript maintenance

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.

error TypeError: Cannot read properties of undefined (reading 'length')
cause 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 Error: ENOENT: no such file or directory, stat '/path/to/your/app/undefined'
cause 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.
error ReferenceError: autoprefixer is not defined
cause 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.
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.
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.
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.
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.
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.
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.
npm install postcss-middleware
yarn add postcss-middleware
pnpm add postcss-middleware

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');
});