How to add custom routes to core routes in Strapi 4

createCoreRouter should have an option to add more routes in the same way as createCoreConroller has. Until then this may helps:

const { createCoreRouter } = require("@strapi/strapi").factories;
const defaultRouter = createCoreRouter("api::store.store");

const customRouter = (innerRouter, extraRoutes = []) => {
  let routes;
  return {
    get prefix() {
      return innerRouter.prefix;
    },
    get routes() {
      if (!routes) routes = innerRouter.routes.concat(extraRoutes);
      return routes;
    },
  };
};

const myExtraRoutes = [
  {
    method: "GET",
    path: "/stores/key",
    handler: "api::store.store.key",
  },
  {
    method: "GET",
    path: "/stores/moreStuff",
    handler: "api::store.store.moreStuff",
  },
];

module.exports = customRouter(defaultRouter, myExtraRoutes);

You can add customRouter to you own libs to reuse it.

16 Likes