Search code examples
reactjskoa

How can I send a React app from a Koa.js server?


I have React app. I have bundle.js and index.html with scripts and a root element. How I can send it from the server?

I have a Koa.js server

const Koa = require('koa');
const app = new Koa();

app.use(async ctx => {
  ctx.body = 'Hello World';
});

app.listen(3000);

Can I send index.html as a static file, or does react have another way?


Solution

  • It's easy. You need to install koa-static. Also have a folder for your static files, for example public, you need to have your reactjs app build there. Then add koa-static middleware to your server, here's a gist of it:

    const Koa = require('koa')
    const serve = require('koa-static')
    
    const app = new Koa();
    app.use(serve(__dirname + '/public'))
    
    app.listen(3000)