Search code examples
node.jsexpresscachinggoogle-cloud-storageasset-pipeline

How to properly pipe Google Cloud Storage asset through Node.js app, to include cache headers and such


So I have this basically (from here):

const { Storage } = require('@google-cloud/storage')
const express = require('express')
const app = express()

const storage = new Storage({
  projectId: 'my-project'
})

const bucket = storage.bucket('my.bucket')

// logo and assets
app.get('/:id.:ext', (req, res) => {
  const remote = bucket.file(`${req.params.id}.${req.params.ext}`)
  remote.createReadStream().pipe(res)
})

I'm wondering what I need to do to set the cache headers or if it automatically somehow happens through the piping. I would like for it to permanently cache some, and 1 month cache others.


Solution

  • If you want to set headers in the response, you'll need to do that using the Express API. Take a look at what you can do with the Response object. You'll likely want to use res.set(). The pipe is just going to deal with the contents of the body of the response.