Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

docs: Pages Router API routes #1161

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open

docs: Pages Router API routes #1161

wants to merge 2 commits into from

Conversation

kjartanhr
Copy link

This pull request adds documentation on how to use translations on the server (API routes) in the pages router.

It is not obvious from current documentation that getTranslations cannot be called from API routes and the error thrown ('getTranslations' is not supported in Client Components) does not indicate any solution, so this section is intended to (partially) close that gap.

I'm unsure if this behaviour is intentional anyway but my proposed documented solution is something I came across in the advanced pages router example, so I'm leaning towards interpereting this as intended behaviour.

Please let me know if there is a better place for this section (maybe a whole page under environments dedicated to the pages router?), as I merely appended it to the file where it seemed to fit best.

I also did not come across any style guide for documentation in your repository, so I apologise in advance if anything I wrote is not up to standard. I'm more than happy to receive feedback and iterate on it :)

Copy link

vercel bot commented Jun 30, 2024

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
next-intl-example-app-router ✅ Ready (Inspect) Visit Preview 💬 Add feedback Jun 30, 2024 9:39pm
next-intl-example-app-router-without-i18n-routing ✅ Ready (Inspect) Visit Preview 💬 Add feedback Jun 30, 2024 9:39pm

Copy link

vercel bot commented Jun 30, 2024

@kjartanhr is attempting to deploy a commit to the next-intl Team on Vercel.

A member of the Team first needs to authorize it.

@amannn
Copy link
Owner

amannn commented Jul 1, 2024

Hey, thanks for proposing this! I think it's a good point to mention this, but I'd considerably give this less prominence in the docs.

I think instead of a separate section, we could add a small expandable block in the route handlers section: "How can I use next-intl in API Routes with the Pages Router?" and link to the core library docs there.

I'd keep it really simple and as a brief explanation instead of coming up with alternative implementations like a synchronous getTranslations (which could be confusing in case you later migrate to the App Router).

Would you like to adjust your proposal?

@kjartanhr
Copy link
Author

Hi again and thanks for the feedback!

I think that's a great way to approach it, I'll adjust my proposal later today and update this pull request with those changes.

Then we can take a look at those changes and see if they need any adjustment as well.

@amannn
Copy link
Owner

amannn commented Aug 21, 2024

Did you by chance have a moment to think about this again @kjartanhr? See my feedback above.

@simplenotezy
Copy link

Thanks for sharing this @kjartanhr. I've adjusted your function a bit:

import { routing } from "@/i18n/routing";
import { createTranslator, NamespaceKeys, NestedKeyOf } from "next-intl";
import { headers as getHeaders } from "next/headers";

/**
 * Workaround to use `getTranslations` in API routes in the pages router.
 *
 * @param opts options containing locale (required) and namespace.
 * @returns translator
 */
export async function getTranslations<
  NestedKey extends NamespaceKeys<
    IntlMessages,
    NestedKeyOf<IntlMessages>
  > = never
>(
  namespace?: NestedKey,
  opts?: {
    locale: string;
  }
) {
  const headers = getHeaders();
  const locale =
    opts?.locale ?? headers.get("accept-language") ?? routing.defaultLocale;

  let messages = {};

  try {
    messages = (await import(`../../messages/${locale}.json`)).default;
  } catch (error) {
    messages = (await import(`../../messages/${routing.defaultLocale}.json`))
      .default;
  }

  return createTranslator({
    locale,
    messages: messages as IntlMessages,
    namespace: namespace,
  });
}

environment.d.ts

import en from "./messages/en.json";

type Messages = typeof en;

declare global {
  // Use type safe message keys with `next-intl`
  interface IntlMessages extends Messages {}
}

And in case you are using i18n-ally, apply: lokalise/i18n-ally#1170

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants