vercel / next.js

The React Framework
https://nextjs.org
MIT License
127.51k stars 27.04k forks source link

Any way to serve files in root path of my domain? #6175

Closed tangbc closed 5 years ago

tangbc commented 5 years ago

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?

tangbc commented 5 years ago

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 ?

lucasfeliciano commented 5 years ago

This is how I do it:

  1. At build time copy the file that you want to serve to .next
  2. Create a route to serve the file
const path = require('path')
router.get('/yourfile.txt', (req, res) => {
  const filePath = path.resolve('.next/yourfile.txt')
  return app.serveStatic(req, res, filePath)
})
tangbc commented 5 years ago

@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'
}
timneutkens commented 5 years ago

It'd actually make Next.js more complex, feel free to write up a RFC for this addition though (issue template feature)

martpie commented 5 years ago

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'))); 
Timer commented 5 years ago

We're adding support for this soon!

Please see https://github.com/zeit/next.js/issues/7177

wiesys commented 5 years ago

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'))); 

Or you can also use Express built-in middleware express.static:

// express instantiation
server.use(express.static('static'));