Node Sass Middleware for Connect/Express

1.1.0 · maintenance · verified Sun Apr 19

node-sass-middleware is a Connect/Express middleware designed to automatically recompile `.scss` or `.sass` files on demand for web servers. It leverages the `node-sass` library (which in turn uses LibSass) to provide on-the-fly compilation, caching, and debugging capabilities directly within a Node.js web application stack. The package's current stable version is 1.1.0, with its latest patch release (v1.1.0) occurring in 2024. While the package itself sees intermittent updates, its core dependency, `node-sass`, is officially deprecated and no longer actively maintained. This means `node-sass-middleware` is primarily suited for maintaining existing projects rather than new development, where modern Dart Sass solutions are generally preferred. It integrates seamlessly into existing Connect or Express applications, offering a convenient bridge between Sass source files and served CSS.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates setting up `node-sass-middleware` with an Express application to compile SASS files on the fly and serve them as static CSS, highlighting the correct middleware order. To run, create a 'sass' directory with a 'main.scss' file (e.g., `body { background-color: lightblue; h1 { color: darkblue; } }`) and an empty 'public' directory in the same location as your script.

const express = require('express');
const sassMiddleware = require('node-sass-middleware');
const path = require('path');
const app = express();

// IMPORTANT: Place sassMiddleware *before* express.static
app.use(sassMiddleware({
    src: path.join(__dirname, 'sass'), // Source directory for .scss/.sass files
    dest: path.join(__dirname, 'public'), // Destination directory for .css files
    debug: true, // Output debugging info to console
    outputStyle: 'compressed', // Minify CSS output
    prefix: '/styles' // CSS will be served from /styles/your_file.css
}));

// Serve static files from the 'public' directory, including compiled CSS
app.use('/styles', express.static(path.join(__dirname, 'public')));

// Example route for demonstration
app.get('/', (req, res) => {
  res.send('<!DOCTYPE html><html><head><link rel="stylesheet" href="/styles/main.css"></head><body><h1>Hello from node-sass-middleware!</h1></body></html>');
});

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
    console.log(`Server listening on port ${PORT}`);
    console.log(`Open http://localhost:${PORT} in your browser.`);
    console.log(`Ensure you have a 'sass' directory with 'sass/main.scss' (e.g., body { h1 { color: darkblue; } }) and an empty 'public' directory.`);
});

view raw JSON →