Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I serve static web site from s3 through node expressjs?

currently I use app.use(express.static('public')) and my files located in the public folder of my node js express app and its working good. However, I would like to store those files (index.html, etc) in my s3 bucket (so multiple apps can use this website). I tried

app.get('/', function(req, res) {
    res.sendfile('link-to-s3-file/index.html'); 
 });

with no success...

like image 452
dang Avatar asked Oct 26 '16 12:10

dang


People also ask

How do I serve a static file in node JS?

In your node application, you can use node-static module to serve static resources. The node-static module is an HTTP static-file server module with built-in caching. First of all, install node-static module using NPM as below. After installing node-static module, you can create static file server in Node.

Can I run NodeJS on S3?

html is the root and files with paths such as js/ css/ images/ taken from the root folder. Note: Its important to understand that you cannot run NodeJS in S3 and instead you will be using the internal web hosting from S3 to serve the static content.

How do I use AWS S3 in node?

We can do this using the AWS management console or by using Node. js. To create an S3 bucket using the management console, go to the S3 service by selecting it from the service menu: Select "Create Bucket" and enter the name of your bucket and the region that you want to host your bucket.


1 Answers

I wouldn't reinvent the wheel. There's a reasonably recent and well documented middleware module for this on npm

From the docs:

app.get('/media/*', s3Proxy({
  bucket: 'bucket_name',
  prefix: 'optional_s3_path_prefix',
  accessKeyId: 'aws_access_key_id',
  secretAccessKey: 'aws_secret_access_key',
  overrideCacheControl: 'max-age=100000'
}));
like image 68
Paul Avatar answered Oct 21 '22 17:10

Paul