Is there any supported way how to deploy a Strapi backend and a ReactJS frontend into a single Heroku app?
I have successfully deployed the Strapi backend, but am complet
In your strapi app create the following files in the following directories:
./middlewares/serve-react/defaults.json
{
"serve-react": {
"enabled": true
}
}
./middlewares/serve-react/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'));
});
},
};
};
./config/middleware.json
{
"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"
]
}
}
If somebody wants to know if Muhammad Ahmad's solution works - yes, it works.
Initially, I worked exclusively with the MERN stack and used two folders - one for the client, the other for the server. Only package.json was at the root. Everything worked fine on Heroku, so I didn't expect to find it difficult to switch the backend to Strapi...
Then I decided to try to replace the server side (Express) to Strapi. After that, there was a problem of deploying this whole case to Heroku and running it on single Heroku application.
So, the project structure is:
/root
- /client (React UI)
- /server (Strapi)
- package.json
In order to make the whole thing work together, it is necessary to amend a little change inside
./middlewares/serve-react/index.js:
const staticDir = path.resolve(strapi.dir, clientBuildPath || strapi.config.paths.static);
where clientBuildPath
is ../client/build.