Search code examples
expresshandlebars.jsprivatesecure-coding

How can I access secure files with express?


nodeapp
   -public
            -CSS
                       -style.css
   -pictures
            -secretImage.png
   -views
            -index.hbs
            -login.hbs
            -profile.hbs
   -server.js

const staticFiles = path.join(__dirname, './public')
app.use(express.static(staticFiles))
app.set('view engine', 'hbs')

I'm keeping my css in the public directory accessed in html like this: href="/css/style.css" which is fine, but I need to store some pictures that should only be available to users that are logged in. If my pictures are in the pictures folder, how can I access them?


Solution

  • You can use the sendFile method...

    app.get('/picture/:pictureName', (req, res) => {
         const valid = /* Do your logic to grant access */
    
         if (valid === false) {
             return res.status(403).send('Not allowed')
         }
    
         res.sendFile('your file path')
    })