Skip to content

Instantly share code, notes, and snippets.

@mulhoon
Last active March 20, 2023 22:42
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mulhoon/9996d992e5c3518134d435372b0f5b96 to your computer and use it in GitHub Desktop.
Save mulhoon/9996d992e5c3518134d435372b0f5b96 to your computer and use it in GitHub Desktop.
Serve S3 files through express proxy
// Example of using express to proxy files from s3.
// Works with streaming media like mp4
const AWS = require('aws-sdk')
const mime = require('mime-types')
const express = require('express')
AWS.config.update({
secretAccessKey: '...',
accessKeyId: '...',
})
const s3 = new AWS.S3({ params: { Bucket: 'bucketname' } })
const app = express()
AWS.Request.prototype.forwardToExpress = function forwardToExpress(res, next, key) {
this.on('httpHeaders', function(code, headers) {
res.status(code)
if (code < 300) {
const newHeaders = {
...headers,
'Content-Type': mime.lookup(key),
}
// Remove some unwanted amazon headers
delete newHeaders['x-amz-id-2']
delete newHeaders['x-amz-request-id']
delete newHeaders['x-amz-meta-modified']
res.set(newHeaders)
}
})
.createReadStream()
.on('error', next)
.pipe(res)
}
app.get('/myfile.mp4', function(req, res, next) {
s3.getObject({
Bucket: 'bucketname',
Key: 'myfile.mp4',
Range: req.headers.range,
}).forwardToExpress(res, next, key)
})
app.listen(8000, () => console.log('App launched on port 8000'))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment