Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Simple connect middleware for simulating url-rewriting for grunt connect servers.
var fs = require('fs'),
url = require('url');
module.exports = function (rootDir, indexFile) {
indexFile = indexFile || "index.html";
return function(req, res, next){
var path = url.parse(req.url).pathname;
fs.readFile('./' + rootDir + path, function(err, buf){
if (!err) return next();
fs.readFile('./' + rootDir + '/' + indexFile, function (error, buffer) {
if (error) return next(error);
resp = {
headers: {
'Content-Type': 'text/html',
'Content-Length': buffer.length
body: buffer
res.writeHead(200, resp.headers);
// Usage example
module.exports = function(grunt) {
var urlRewrite = require('grunt-connect-rewrite');
// Project configuration.
connect: {
server: {
options: {
port: 9001,
base: 'build',
middleware: function(connect, options) {
// Return array of whatever middlewares you want
return [
// redirect all urls to index.html in build folder
urlRewrite('build', 'index.html'),
// Serve static files.
// Make empty directories browsable.
grunt.registerTask('default', ['connect']);
Copy link

marfarma commented Oct 24, 2013

see my fork for a version that optionally allows the base directory to be '.' - i.e. index.html is in the same directory as your Gruntfile.

Copy link

Thinkscape commented Dec 8, 2013

Thank you!

Copy link

carlholloway commented Jan 5, 2014

@muratcorlu thank you for this!

Copy link

mrdavenz commented Feb 12, 2015

Is there anything else required to get this working, when I implemented this GIST, the grunt script runner kicked up the error ">> Error: Cannot find module 'grunt-connect-rewrite'"

Copy link

dennisbosma commented May 18, 2015

I'm new to Grunt and I got the same prolem as mrdavenz

Copy link

Mr-Chilly commented Jul 1, 2015

For those who can't get this script to work:

Place the grunt-connect-rewrite.js file in your bower_components folder.

The 'require('grunt-connect-rewrite');' is referencing the script there. You can then use it in your grunt tasks

Copy link

WhyTree-EdonBajrami commented Jul 18, 2015

Shows me an error "Object build has no method 'initConfig' Use --force to continue."

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment