Created custom route findBySlug - querying the non-default locale slug is not working | Strapi v5

Hi, I am building a Blog with Strapi and I am having issues with i18n. When I am querying my default language “DE” everything works fine but when I do it reverse and as soon as I try to query the non default language I am getting a 404.

Now I need some help to continue, why is that happening. Is my approach wrong? Maybe there is a better approach, looking forward to you suggestions :slightly_smiling_face:

const { createCoreController } = require(“@strapi/strapi”).factories;

module.exports = createCoreController(
“api::category.category”,
({ strapi }) => ({
async findBySlug(ctx) {
const { slug } = ctx.params;

  const query = {
    filters: { slug },
  };

  const categories = await strapi.entityService.findMany(
    "api::category.category",
    query
  );

  if (!categories || categories.length === 0) {
    return ctx.notFound();
  }

  const category = categories[0];

  if (category.locale === ctx.query.locale || !ctx.query.locale) {
    const sanitizedEntity = await this.sanitizeOutput(category);
    return this.transformResponse(sanitizedEntity);
  } else {
    // If the locale is not the same as the query locale, try to find the category in the query locale with the documentId
    const query = {
      filters: {
        documentId: category.documentId,
        locale: ctx.query.locale,
      },
    };

    const localizedCategories = await strapi.entityService.findMany(
      "api::category.category",
      query
    );

    if (!localizedCategories || localizedCategories.length === 0) {
      return ctx.notFound();
    }

    const localizedCategory = localizedCategories[0];
    const sanitizedEntity = await this.sanitizeOutput(localizedCategory);

    return this.transformResponse(sanitizedEntity);
  }
},

})
);

This topic has been created from a Discord post (1295444591511867412) to give it more visibility.
It will be on Read-Only mode here.
Join the conversation on Discord

Is there a way to get the same behaviour as with documentId to that controller?

Found a workaround but still don’t know if it is the best practise.

I have created a new field localizedSlugs that contains json and on creation I enter the slugs by hand:
{
“en”: “english-slug”,
“de”: “german-slug”
}

With that I have mapped the slugs to the other posts and this allows me to use findBySlug.

Is there a way to reduce the effort to not do it by hand?

Maybe with a lifecycle hook?