Search code examples
javascriptnode.jsamazon-s3expressappfog

Streaming Assets (JS/CSS/images) from Amazon S3 with Express.js


I recently deployed my Node.js blog on AppFog. I plan to use a bucket on Amazon S3 to stream my assets (javascript/stylesheets/images).

How can I make sure that Express.js get static assets to my Amazon S3 bucket instead of the regular /public?


Solution

  • I wouldn't stream assets through the node server – it's a waste of resources, and you're going to have to deal with HTTP caching headers.

    Instead, your HTML should link directly to the S3 bucket. Instead of:

    <script src="/js/script.js"></script>
    

    Do:

    <script src="//s3.amazonaws.com/bucket/js/script.js"></script>
    

    Given that you're migrating, just set up a permanent redirect.

    app.get(/^\/(js|css|images)\/.*/, function(req, res) {
        res.redirect(301, '//s3.amazonaws.com/bucket' + req.path);
    });
    

    This will redirect all requests for things in the js, css, and images folders to a S3 bucket. For example, /js/script.js would redirect to //s3.amazonaws.com/bucket/js/script.js.

    This will help ease the transition, but you should still migrate your site's references to the S3 URLs to eliminate the unnecessary HTTP roundtrip cause by having the redirect.