Search code examples
javascriptnode.jskoakoa-routerkoa-static

Why can't I serve static files from a Koa router?


Why in the following case does koa-static fail to work with koa-router?

const Koa = require("koa")
const serve = require("koa-static")
const Router = require("koa-router")

const app = new Koa()
const router = new Router()

// fails with 404... why?
router.use(serve("public"))

// // this, on the other hand, works
// app.use(serve("public"))

app.use(router.middleware())
app.listen(8080)

// browse to "http://localhost:8080/testfile.txt"

I made this GitHub repo to demo the issue: koa-router-static-issue


Solution

  • This is essentially how we have stuff configured in our app.

    It uses koa-mount to mount the static file server at a particular root URL. If your static file URLs overlap the namespace of your routes, the static files win.

    const Koa    = require('koa')
    const Router = require('koa-router')
    const serve  = require('koa-static')
    const mount  = require('koa-mount')
    
    const app    = new Koa()
    const router = new Router()
    
    router.get('/public/foobar.txt', (ctx,next) => {
    
      ctx.body   = "Ta-Da!"
      ctx.status = 200
    
      return;
    })
    
    app.use( mount( '/public', serve('./public') ) ) ;
    app.use( router.middleware())
    
    app.listen( 8080 ) ;