NextJS does not recognize dynamically added static assets in production

Viewed 747

I'm running a two container docker setup; NextJS for the public facing web, and Django backend for admins to add content. The routes are nicely working with getInitialProps which fetches the added content. As the content references static images, they are connected via docker volumes (./static/media on django container and ./public/media on nextjs container).

However when a new image appears in ./public/media, the started NextJs server returns a 404 response for those images.

// EDITED SOLUTION: As suggested by @Pierfrancesco

The workaround solution is to create a custom server which dynamically serves those files

// server.js
const express = require('express')
const next = require('next')

const port = parseInt(process.env.PORT, 10) || 3000
const dev = process.env.NODE_ENV !== 'production'
const app = next({ dev })
const handle = app.getRequestHandler()

app.prepare().then(() => {
  const server = express()

  server.get('/media/images/*', (req, res) => {
    // Disallow travelling up in the file tree
    let target = req.originalUrl.replace("..", "")
    return res.sendFile(__dirname + '/public' + target);
  })

  server.all('*', (req, res) => {
    return handle(req, res)
  })

  server.listen(port, err => {
    if (err) throw err
    console.log(`> Ready on http://localhost:${port}`)
  })
})

Could this be a feature request or is this a bug in NextJS?

0 Answers
Related