score:2

Accepted answer

using 3.0.0.beta.19.5 to deploy strapi + react in the same server you need to do the following things.

rootdir = means the root folder of the strapi project.

you need to create a new middleware, rootdir/middlewares/serve-react, and this 2 files in there.

  1. defaults.json
{
  "serve-react": {
    "enabled": true
  }
}
  1. index.js
'use strict';

/**
 * module dependencies
 */

// node.js core.
const fs = require('fs');
const path = require('path');
const koastatic = require('koa-static');

/**
 * serve react hook
 */

module.exports = strapi => {

  return {
    /**
     * initialize the hook
     */

    async initialize() {
      const {maxage, path: publicpath} = strapi.config.middleware.settings.public;
      const staticdir = path.resolve(strapi.dir, publicpath || strapi.config.paths.static);

      strapi.router.get(
        '/*',
        async (ctx, next) => {
          const parse = path.parse(ctx.url);
          ctx.url = path.join(parse.dir, parse.base);

          await next();
        },
        koastatic(staticdir, {
          maxage: maxage,
          defer: false, // do not allow other middleware to serve content before this one
        })
      );

      // if no resource is matched by koa-static, just default to serve index file
      // useful for spa routes
      strapi.router.get('*', ctx => {
        ctx.type = 'html';
        ctx.body = fs.createreadstream(path.join(staticdir + '/index.html'));
      });
    },
  };
};

add the middleware just created in the chain. rootdir/config/middleware.json. notice the "serve-react" at the end of the "after" property, is the only thing added in this case.

{
  "timeout": 100,
  "load": {
    "before": [
      "responsetime",
      "logger",
      "cors",
      "responses",
      "gzip"
    ],
    "order": [
      "define the middlewares' load order by putting their name in this array is the right order"
    ],
    "after": [
      "parser",
      "router",
      "serve-react"
    ]
  }
}

Related Query

More Query from same tag