Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8370939
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 9, 20262026-06-09T14:02:05+00:00 2026-06-09T14:02:05+00:00

I’m setting up the structure of a new project which will be built using

  • 0

I’m setting up the structure of a new project which will be built using Node.js and Express. I ‘m using HTML5 Boilerplate for an optimal starting point. It comes with configuration files for multiple types of servers: Apache, Nginx, Node.js, etc. The following is the Node.js server configuration file provided by the HTML5 Boilerplate team:

/* h5bp server-configs project
 *
 * maintainer: @xonecas
 * contributors: @niftylettuce
 *
 * NOTES:
 * compression: use the compress middleware provided by connect 2.x to enable gzip/deflate compression
 *                          http://www.senchalabs.org/connect/compress.html
 *
 * concatenation: use on of the following middlewares to enable automatic concatenation of static assets
 *                              - https://github.com/mape/connect-assetmanager
 *                              - https://github.com/TrevorBurnham/connect-assets
 */
var h5bp    = module.exports,
   _http    = require('http'),
   _parse   = require('url').parse;

// send the IE=Edge and chrome=1 headers for IE browsers
// on html/htm requests.
h5bp.ieEdgeChromeFrameHeader = function () {
   return function (req, res, next) {
      var url = req.url,
         ua = req.headers['user-agent'];

      if (ua && ua.indexOf('MSIE') > -1 && /html?($|\?|#)/.test(url)) {
         res.setHeader('X-UA-Compatible', 'IE=Edge,chrome=1');
      }
      next();
   };
};

// block access to hidden files and directories.
h5bp.protectDotfiles = function () {
   return function (req, res, next) {
      var error;
      if (/(^|\/)\./.test(req.url)) {
         error = new Error(_http.STATUS_CODES[405]); // 405, not allowed
         error.status = 405;
      }
      next(error);
   };
};

// block access to backup and source files
h5bp.blockBackupFiles = function () {
   return function (req, res, next) {
      var error;
      if (/\.(bak|config|sql|fla|psd|ini|log|sh|inc|swp|dist)|~/.test(req.url)) {
         error = new Error(_http.STATUS_CODES[405]); // 405, not allowed
         error.status = 405;
      }
      next(error);
   };
};

// Do we want to advertise what kind of server we're running?
h5bp.removePoweredBy = function () {
   return function (req, res, next) {
      res.removeHeader('X-Powered-By');
      next();
   };
};

// Enable CORS cross domain rules, more info at http://enble-cors.org/
h5bp.crossDomainRules = function () {
   return function (req, res, next) {
      res.setHeader('Access-Control-Allow-Origin', '*');
      res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With');
      next();
   };
};

// Suppress or force 'www' in the urls
// @param suppress = boolean
h5bp.suppressWww = function (suppress) {
   return function (req, res, next) {
      var url = req.url;
      if (suppress && /^www\./.test(url)) {
         res.statusCode = 302;
         res.setHeader('Location', url.replace(/^www\./,''));
      }
      if (!suppress && !/^www\./.test(url)) {
         res.statusCode = 302;
         res.setHeader('Location', "www."+url);
      }
      next();
   };
};

// Far expire headers
// use this when not using connect.static for your own expires/etag control
h5bp.expireHeaders = function (maxAge) {
   return function (req, res, next) {
      res.setHeader('Cache-Control', 'public, max-age='+ (maxAge));
      next();
   };
};

// Etag removal
// only use this is you are setting far expires for your files
// ** WARNING ** connect.static overrides this.
h5bp.removeEtag = function () {
   return function (req, res, next) {
      res.removeHeader('Last-Modified');
      res.removeHeader('ETag');
      next();
   };
};

// set proper content type
// @param mime = reference to the mime module (https://github.com/bentomas/node-mime)
h5bp.setContentType = function (mime) {
   return function (req, res, next) {
      // I'm handling the dependency by having it passed as an argument
      // we depend on the mime module to determine proper content types
      // connect also has the same dependency for the static provider
      // ** @TODO ** maybe connect/express expose this module somehow?
      var path = _parse(req.url).pathname,
         type  = mime.lookup(path);
      res.setHeader('Content-Type', type);
      next();
   };
};

// return a express/connect server with the default middlewares.
// @param serverConstructor = express/connect server instance
// @param options = {
//    root: 'path/to/public/files',
//    maxAge: integer, time in miliseconds ex: 1000 * 60 * 60 * 24 * 30 = 30 days,
//    mime: reference to the mime module ex: require('mime')
// }
// Depends:
//    express or connect server
//    mime module [optional]

h5bp.server = function (serverConstructor, options) {
   var server = serverConstructor.createServer(),
       stack = [
         this.suppressWww(true),
         this.protectDotfiles(),
         this.blockBackupFiles(),
         this.crossDomainRules(),
         this.ieEdgeChromeFrameHeader()
      //,this.expireHeaders(options.maxAge),
      // this.removeEtag(),
      // this.setContentType(require('mime'))
       ];
   // express/connect
   if (server.use) {
      stack.unshift(serverConstructor.logger('dev'));
      stack.push(
         //serverConstructor.compress(), // express doesn't seem to expose this middleware
         serverConstructor['static'](options.root, { maxAge: options.maxAge }), // static is a reserved
         serverConstructor.favicon(options.root, { maxAge: options.maxAge }),
         serverConstructor.errorHandler({
            stack: true,
            message: true,
            dump: true
         })
      );
      for (var i = 0, len = stack.length; i < len; ++i) server.use(stack[i]);
   } else {
      server.on('request', function (req, res) {
         var newStack = stack,
             func;
         (function next (err) {
            if (err) {
               throw err;
               return;
            } else {
               func = newStack.shift();
               if (func) func(req, res, next);
               return;
            }
         })();
      });
   }
   return server;
};

My question is this: how exactly do I go about integrating this with Express? The section of code that specifically confuses me is the bottom portion:

// return a express/connect server with the default middlewares.
// @param serverConstructor = express/connect server instance
// @param options = {
//    root: 'path/to/public/files',
//    maxAge: integer, time in miliseconds ex: 1000 * 60 * 60 * 24 * 30 = 30 days,
//    mime: reference to the mime module ex: require('mime')
// }
// Depends:
//    express or connect server
//    mime module [optional]

h5bp.server = function (serverConstructor, options) {
   var server = serverConstructor.createServer(),
       stack = [
         this.suppressWww(true),
         this.protectDotfiles(),
         this.blockBackupFiles(),
         this.crossDomainRules(),
         this.ieEdgeChromeFrameHeader()
      //,this.expireHeaders(options.maxAge),
      // this.removeEtag(),
      // this.setContentType(require('mime'))
       ];
   // express/connect
   if (server.use) {
      stack.unshift(serverConstructor.logger('dev'));
      stack.push(
         //serverConstructor.compress(), // express doesn't seem to expose this middleware
         serverConstructor['static'](options.root, { maxAge: options.maxAge }), // static is a reserved
         serverConstructor.favicon(options.root, { maxAge: options.maxAge }),
         serverConstructor.errorHandler({
            stack: true,
            message: true,
            dump: true
         })
      );
      for (var i = 0, len = stack.length; i < len; ++i) server.use(stack[i]);
   } else {
      server.on('request', function (req, res) {
         var newStack = stack,
             func;
         (function next (err) {
            if (err) {
               throw err;
               return;
            } else {
               func = newStack.shift();
               if (func) func(req, res, next);
               return;
            }
         })();
      });
   }
   return server;
};

My JavaScript isn’t exactly at a beginners level but I wouldn’t say I’m advanced either. This code is beyond me. Any pointers as to what I can read, watch, or do, to learn what I’m obviously missing here would be appreciated.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-09T14:02:07+00:00Added an answer on June 9, 2026 at 2:02 pm

    Most of the file is made up of a series of functions that generate middleware for frameworks, like Express, that conform to Connect’s middleware specification. The second code listing is designed to create an HTTP server that uses all these functions. From what I can tell, it looks like you’re supposed to pass in whatever you would normally call createServer on, and h5bp will do the creation and setup for you. For example, if you would normally do:

    var express = require('express');
    var server = express.createServer();
    

    You would instead pass express to h5bp.server, which calls createServer on whatever you pass in right off the bat:

    var express = require('express');
    var server = h5bp.server(express, options);
    

    After a bit of setup, it checks to see if the server has a function called use (the line is if (server.use)), and if so uses it to inject all the middleware it set up into the server. If it doesn’t, then it assumes you’re using a raw Node.js HTTP server, and sets up the necessary code to pass the request through each of the items in stack manually (this is what Connect/Express does for you).

    It’s worth noting that, in Express 3 (currently in release candidate stage), the applications created by Express no longer inherit from Node’s HTTP server, so you don’t call createServer on express; instead, you should just call express() and then pass the results of that into http.createServer. (See “Application function” at Migrating from 2.x to 3.x on the Express wiki for more information.) This means that this script is not compatible with the latest version of Express.

    [update]

    If you take a look at the test directory on GitHub, you can see an example app:

    var express = require('express'),
       h5bp     = require('../node.js'),
       server   = h5bp.server(express, { 
          root: __dirname,
          maxAge: 1000 * 60 * 60 * 30
       });
    
    server.listen(8080);
    console.log('ok');
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I want use html5's new tag to play a wav file (currently only supported
link Im having trouble converting the html entites into html characters, (&# 8217;) i
That's pretty much it. I'm using Nokogiri to scrape a web page what has
I am trying to understand how to use SyndicationItem to display feed which is
I used javascript for loading a picture on my website depending on which small
I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
I am reading a book about Javascript and jQuery and using one of the
I'm using v2.0 of ClassTextile.php, with the following call: $testimonial_text = $textile->TextileRestricted($_POST['testimonial']); ... and
I would like to run a str_replace or preg_replace which looks for certain words
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.