Search code examples
node.jskoa

How to specify a static folder in Koa only when using a specific route?


I've noticed Koa's middleware such as koa-static (https://github.com/koajs/static) does not support serving a a static folder when using a specific route such as "dashboard", it seems to only support serving static folder globally...what might be the best solution to this challenge?

For example, I can try:

app.use(...)
   .use(async function(ctx){
      if ('/dashboard' === ctx.path) {
        let body = await static('./build');
        return body;
      }
   });

OR

app.use(...)
   .use(async function(ctx){
      if ('/dashboard' === ctx.path) {
        await static('./build');
      }
   });

the result is simply "Not Found".


Solution

  • Use koa-mount:

    npm i koa-mount
    
    const mount = require('koa-mount');
    
    ...
    .use(mount('/dashboard', static('./build')));