Customize /api prefix for APIs

System Information
  • Strapi Version: 4.0.0
  • Operating System: Windows 10
  • Database: sqlite
  • Node Version: v14.15.1
  • NPM Version: 6.14.8
  • Yarn Version: 1.22.5

Is it possible to customize the /api prefix for Strapi API routes? In case it’s relevant, I installed Strapi using the command outlined in the Quick Start Guide: npx create-strapi-app@latest my-project --quickstart

My use case is that my server is already on a subdomain like api.example.com, so the /api path is not necessary. Ideally, I’d like to remove it, but renaming could work also.

Thanks!

1 Like

AFAIK it can’t be set to / anymore (I think it’s a bug but need to talk to engineers).

It’s undocumented atm but in ./config/api.js inside of the rest object set prefix: '/whatever' and that should change the prefix.

(suggest maybe something like /v1 or whatever)

1 Like

Thank you, this does work. You are also correct that / doesn’t work, even if combined with prefix at the route level (so, for example, it does not seem possible to have some routes with /prefix1 and others with /prefix2.

To whoever encounters this same problem and is a bit confused about where to find and do this, I got it here:


I just typed @DMehaffy solution inside the rest object because it doesn’t exist
Thank you, this solution solved my problem

Yeah - it’s a regression and if other applications depended on querying against the naked domain, those will break unless updated (which increases the migration complexity considerably).

Did you receive any feedback from engineering on this?

I didn’t :confused: It might be possible to handle via a reverse proxy (like nginx) but I haven’t attempted to make a config to test that theory.

Hi @CEB3895, @DMehaffy ,
Thanks.The solution to add the prefix works for the rest api. But my admin is breaking as its throwing an error for the i18n/locales api. I am using below config as I don’t need any prefix.

 rest: {
    prefix: ''
  }


Any idea how to solve this issue?

AFAIK it’s not possible to completely remove the prefix in Strapi v4

Thanks @DMehaffy. Anyways I only wanted to REST apis to work which doesn’t have /api prefix as I am migrating my code from V3 to V4. I have achieved it using custom middleware as all my REST endpoint has a header x-store-id

module.exports = () => {
  return async (ctx, next) => {
    if (!ctx.request.url.toString().startsWith('/api') && ctx.request.header['x-store-id']) {
      ctx.request.url = '/api' + ctx.request.url;
    }

    await next();
  };
};

1 Like