Hi~
I have look at static-file-serving, but it must put files in static folder.
If I need put a file verify_xx.txt in root path of my domain to visit it, such as www.abc.com/verify_xx.txt where nextjs deploy at www.abc.com, how can I do?
except write a special node/koa router for all these files?
I have put verify_xx.txt inside static folder, then I try this way but failed:
...
const app = next({
dir: path.resolve(__dirname, '../'),
dev: process.env.NODE_ENV === 'development'
})
const defaultHandler = app.getRequestHandler()
router.get('*', async context => {
const { req, res } = context
let { path } = context.request
if (path.indexOf('/verify_xx.txt') === 0) {
path = `/static${path}` // try to serve as /static/*
console.log('path: ', path) // output is: /static/verify_xx.txt
await defaultHandler(req, res, path)
} else {
await defaultHandler(req, res)
}
context.respond = false
})
...
I visit localhost:8080/verify_xx.txt is error but I visit localhost:8080/static/verify_xx.txt is right.
Where is the problem here ?
This is how I do it:
.nextconst path = require('path')
router.get('/yourfile.txt', (req, res) => {
const filePath = path.resolve('.next/yourfile.txt')
return app.serveStatic(req, res, filePath)
})
@lucasfeliciano Thanks, it works!
I use:
path.resolve(`static${path}`)
It would be great if nextjs could done this just by a simple config, for example in next.config.js:
module.exports = {
rootServeDir: 'rootAssets'
}
It'd actually make Next.js more complex, feel free to write up a RFC for this addition though (issue template feature)
For those looking for a one-line-do-it-all solution without having to write five lines of server.get per file in the static folder:
const serveStatic = require('serve-static');
... // express instantiation
server.use(serveStatic(path.resolve('./static')));
We're adding support for this soon!
Please see https://github.com/zeit/next.js/issues/7177
For those looking for a one-line-do-it-all solution without having to write five lines of
server.getper file in the static folder:const serveStatic = require('serve-static'); ... // express instantiation server.use(serveStatic(path.resolve('./static')));
Or you can also use Express built-in middleware express.static:
// express instantiation
server.use(express.static('static'));