Next.js: Any way to serve files in root path of my domain?

Created on 30 Jan 2019  路  7Comments  路  Source: vercel/next.js

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?

All 7 comments

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:

  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)
})

@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.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'));
Was this page helpful?
0 / 5 - 0 ratings

Related issues

YarivGilad picture YarivGilad  路  3Comments

ghost picture ghost  路  3Comments

knipferrc picture knipferrc  路  3Comments

lixiaoyan picture lixiaoyan  路  3Comments

olifante picture olifante  路  3Comments