node.jsreactjswebpackkoakoa-router

How to serve the same static files regardless of the route?


I have a react App. With webpack I build for production. Now I try to set a little koa server to serve the static files generated by webpack for production.

So I did this

import Koa from 'koa'
import serve from 'koa-static'

const app = new Koa()

app.use(serve('dist/'))

app.listen(3001)

Where dist/ is the directory where are the files (index.html, bundle etc). This works well but only for the route '/' (localhost:3001/) In my app I use react router so I need to go to /login (localhost:3001/login) by example. But when I try I get "Not Found". With the devServer (by webpack) this route works well. I just need to always serve /dist, whatever the route. How to do this whit koa ?


Solution

  • Ok I finally won

    import Koa from 'koa'
    import serve from 'koa-static'
    import fs from 'fs'
    import path from 'path'
    
    const app = new Koa()
    const dist = path.join(__dirname, 'dist')
    let validRoutes
    
    fs.readdir(dist, (err, files) => {
      if (err) return console.log('Unable to scan directory: ' + err)
      validRoutes = files
    })
    
    function isRouteValid (url) {
      if (!validRoutes || !url) return false
      return validRoutes.find(route => url.slice(1) === route)
    }
    
    app.use(async (ctx, next) => {
      if (!isRouteValid(ctx.url)) ctx.path = 'index.html'
      await next()
    })
    
    app.use(serve(dist))
    
    app.listen(3010)