serveStatic API doesn't work as expected since 9.3.2
See original GitHub issueBug report
Describe the bug
When using a custom server, the API app.serveStatic(req, res, filePath) is used to return static files, but the server returns a 404 error page, even though the file is present on disk.
I’m using a custom server.js to run next and serve a service worker config produced at runtime by next-offline.
After upgrading from 9.3.1 to 9.3.2, the file cannot be served as the server returns a 404.
To Reproduce
With the following server.js:
const fs = require("fs")
const { createServer } = require("http")
const { join } = require("path")
const { parse } = require("url")
const next = require("next")
const app = next({ dev: process.env.NODE_ENV !== "production" })
const handle = app.getRequestHandler()
app.prepare().then(() => {
createServer((req, res) => {
const parsedUrl = parse(req.url, true)
const { pathname } = parsedUrl
if (pathname === "/service-worker.js") {
const filePath = join(__dirname, ".next", pathname)
console.log({
filePath,
exists: fs.existsSync(filePath),
files: fs.readdirSync(join(__dirname, ".next")),
})
app.serveStatic(req, res, filePath)
} else {
handle(req, res, parsedUrl)
}
}).listen(3000, () => {
console.log(`> Ready on http://localhost:${3000}`)
})
})
in your shell run
rm -rf node_modules .next
yarn add next@9.3.1
node server.js
The file content is correctly served at http://localhost:3000/service-worker.js
Then run:
rm -rf node_modules .next
yarn add next@9.3.2
node server.js
The url http://localhost:3000/service-worker.js returns a 404 and shows the default error page.
Expected behavior
The file should be served consistently accross versions
Screenshots
N/A
System information
- OS: linux ubuntu 18.04
- Browser (if applies): any
- Version of Next.js: 9.3.2
Additional context
Here is the console.log extract from server.js showing that the file is present when the 404 is returned:
{ filePath:
'/pathtomyproject/.next/service-worker.js',
exists: true,
files:
[ 'build-manifest.json',
'cache',
'react-loadable-manifest.json',
'server',
'service-worker.js',
'static' ] }
Issue Analytics
- State:
- Created 3 years ago
- Reactions:4
- Comments:12 (5 by maintainers)

Top Related StackOverflow Question
For those who’s looking for the solution, checkout this https://github.com/zeit/next.js/issues/11624#issuecomment-608411836
This works for me.
I’m uploading files to /public but I can’t serve anymore those files (404) unless I trigger a rebuild. Is there is any way to dynamically server files?