Deploying client side applications to S3 with Grunt

If you are developing static client side applications then S3 is the perfect place to host them – it is cheap and massively scalable especially if you use CloudFront.

Using Grunt and grunt-aws-s3 also makes it incredibly easy to deploy these apps.

I’m going to assume you already have nodejs and Grunt installed and ready to go, so lets start by adding the grunt-aws-s3 plugin:

Once that is installed you can enable it inside your Gruntfile by adding the following:

Now you need to create an S3 bucket to deploy to and an IAM user and policy to give Grunt permission to deploy to it.

When you create the new IAM user you should generate new keys, place the access key, secret key and your S3 bucket region into a file named deploy-keys.json (Make sure you place this file in your .gitignore – you should never commit API keys) in the same directory as your Gruntfile and in the following format:

Attach the following IAM policy to your newly created user where is the name of the S3 bucket you have created:

You can now add the following to your grunt.initConfig to setup the deploy task:

Refer to the grunt-aws-s3 documentation for further configuration options, you may also like to change the files cwd to a sub folder such as /dist or /www if you have Grunt running a build step into a sub directory.

You can now deploy your application to S3 by running the following:

Most likely you will want to run a few other grunt tasks before deploying like linting or building so you should register a task like so:

Now you have a deploy task which will run jshint and build your project before deploying it to S3 (obviously you will need to have registered tasks for jshint and build for this to work) :

This task can now be run whenever you need to push a new version of your application live.

A final tip – If you are using jshint or any other linter with your project and have it set to enforce camel case variable names you may find that it does not like the “aws_s3” key used inside the grunt.initConfig block – this is easy to fix by adding the following to your Gruntfile:

You can now go through the rest of your Gruntfile and replace all references to “aws_s3” with “s3Deploy” and you will receive no more linting errors.