sergiodxa / remix-i18next

The easiest way to translate your Remix apps
https://sergiodxa.github.io/remix-i18next/
MIT License
616 stars 44 forks source link

RemixI18Next.getRouteNamespaces returns every namespace instead of matched routes #217

Open jrestall opened 2 months ago

jrestall commented 2 months ago

Describe the bug

The docs for getRouteNamespaces imply that it only returns the namespaces for the current request, however we are finding it returns every namespace in our app.

This causes the server to load a lot more namespaces from an http backend than necessary to serve the current request which impacts performance.

Perhaps it should use the current route matches instead of all routeModules instead,

e.g.

function getRouteNamespaces(context: EntryContext): string[] {
  const namespaces = Object.values(
    context.staticHandlerContext.matches
  ).flatMap((match) => {
    const route = match.route;

    if (typeof route?.handle !== "object") return [];
    if (!route.handle) return [];
    if (!("i18n" in route.handle)) return [];
    if (typeof route.handle.i18n === "string") return [route.handle.i18n];

    if (
      Array.isArray(route.handle.i18n) &&
      route.handle.i18n.every((value: string) => typeof value === "string")
    ) {
      return route.handle.i18n as string[];
    }

    return [];
  });

  return [...new Set(namespaces)];
}

Your Example Website or App

Can create if necessary.

Steps to Reproduce the Bug or Issue

  1. Follow the standard remix-18next setup.
  2. Create a Remix app with many separate localization namespaces.
  3. Note that all namespaces are returned by getRouteNamespaces for each request.

    **let ns = i18next.getRouteNamespaces(remixContext);**
    
    await instance
    .use(initReactI18next) // Tell our instance to use react-i18next
    .use(Backend) // Setup our backend
    .init({
      ...i18n, // spread the configuration
      lng, // The locale we detected above
      ns, // The namespaces the routes about to render wants to use
      backend: { loadPath: resolve("./public/locales/{{lng}}/{{ns}}.json") },
    });

Expected behavior

As a developer, I expect only the namespaces required for the current matched routes to be returned.

Screenshots or Videos

No response

Platform

NodeJS 20+

Additional context

No response