11

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

ChaseMoskal
  • 7,151
  • 5
  • 37
  • 50

2 Answers2

8

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 ) ;
Nicholas Carey
  • 71,308
  • 16
  • 93
  • 135
  • 1
    Nicholas, that's fine for static paths but the benefits of the router allow for dynamic route parameters. For example, consider a multi-tenant app -/public/:tenant/:site/:slug* - because the static is mounted to the app, and not router middleware, you can't use dynamic paths. Thoughts? – Tremendus Apps Jun 10 '19 at 15:17
1

Another option is to wrap the static folder in a way that it can serve as a fallback for router...

const router = Router();
router.get('/', (ctx) => { ctx.body = 'Hello World!' });
app.use(serve('/tmp'));
app.use(router.routes());

In that example going to / would take you to helloWorld, and fallback to any files in /tmp/

source: https://github.com/ZijianHe/koa-router/issues/446

Ray Foss
  • 3,649
  • 3
  • 30
  • 31