Search code examples
javascriptreactjshttp-redirectreact-routerstrapi

Strapi custom routes to redirect to public directory


I deployed my react app to /public directory in strapi, everything work's correctly but, when I refreshed page, strapi override my react-router routs.

So... how can I redirect strapi to open public directory when i use specific routs?

e.g redirect /posts to public directory?


Solution

  • Strapi /public folder is here to server public assets and not to host your front end application. And it's not a good practice to do that. I had to write that before answering your question.

    Here is how static files are served. https://github.com/strapi/strapi/blob/master/packages/strapi/lib/middlewares/public/index.js It uses the public middleware.

    So you will have to create your own middleware by following this documentation. https://strapi.io/documentation/3.x.x/advanced/middlewares.html#custom-middlewares

    So in ./middelwares/custom/index.js add the following code:

    const path = require('path');
    
    module.exports = strapi => {
      return {
        initialize: function(cb) {
          strapi.router.route({
            method: 'GET',
            path: '/post',
            handler: [
              async (ctx, next) => {
                ctx.url = path.basename(`${ctx.url}/index.html`);
    
                await next();
              },
              strapi.koaMiddlewares.static(strapi.config.middleware.settings.public.path || strapi.config.paths.static, {
                maxage: strapi.config.middleware.settings.public.maxAge,
                defer: true
              })
            ]
          });
    
          cb();
        }
      };
    };
    

    Then you will have to enable your middleware. You will have to update the ./config/custom.json file with the following code:

    {
      "myCustomConfiguration": "This configuration is accessible through strapi.config.myCustomConfiguration",
      "custom": {
        "enabled": true
      }
    }
    

    That's it!