amannn / next-intl

🌐 Internationalization (i18n) for Next.js
https://next-intl-docs.vercel.app
MIT License
2.58k stars 236 forks source link

Errors/Warnings during build #87

Closed silvestreh closed 2 years ago

silvestreh commented 2 years ago

Hey there! First off I'd like to say thanks for the library and, at the same time, apologize if this isn't the right place for questions.

I've been using this library to translate a website and during build time on Netlify I keep seeing these errors:

NOTIFY Error: [missing key] languages.es
    at handleMessageFallback

This happens for every key, but they're not missing as the site renders properly in all available languages. All static pages are translated (I checked the HTML files Next generated.)

Our _app.js uses the provider like this:

import { NextIntlProvider, IntlErrorCode } from 'next-intl';
import Bugsnag, { ErrorBoundary } from '@/bugsnag'
import ErrorPage from '@/pages/_error';

const MyApp = ({ Component, pageProps }) => {
  const handleIntlError = error => {
    if (error.code !== IntlErrorCode.MISSING_MESSAGE) {
      Bugsnag.notify(error);
    }
  };

  const handleMessageFallback = ({ namespace, key, error }) => {
    if (process && process.env.NODE_ENV !== 'production') {
      return `[missing key] ${namespace}.${key}`;
    }

    if (error.code === IntlErrorCode.MISSING_MESSAGE) {
      Bugsnag.notify(new Error(`[missing key] ${namespace}.${key}`));
      return key;
    }
  };

  return (
    <ErrorBoundary FallbackComponent={ErrorPage}>
      <NextIntlProvider messages={pageProps.messages} onError={handleIntlError} getMessageFallback={handleMessageFallback}>
        <Component {...pageProps} />
      </NextIntlProvider>
    </ErrorBoundary>
  );
};

export default MyApp;

If I console.log(pageProps.messages) all the keys are logged as expected. Client and server side.

On pages I'm accessing messages through getStaticProps and getServerSideProps by returning a messages prop:

export async function getServerSideProps ({ locale }) {
  return {
    props: {
      messages: require(`@/locales/${locale}.json`)
    }
  };
}

Let me know if you need more info. I tried to simplify the snippets by removing unrelated code.

Thanks!

amannn commented 2 years ago

Hi and thanks for the report!

There was a similar error reported in https://github.com/amannn/next-intl/issues/32 by @Pixelatex and @timonweber replied in the thread more recently with the same issue. Not sure if they figured out the issue eventually?

In any case it would be very helpful if you could include a reproduction like it's mentioned in the issue template, otherwise it's pretty hard to diagnose. Thanks!

amannn commented 2 years ago

Closing due to inactivity … Please provide a reproduction if you're still seeing this error!

LunarMelody commented 2 years ago

I was moving away from i18next to next-intl, and I came across the issue myself too, and for me it was happening due to a use of a component inside of _app.tsx which use the useTranslations() hook. I also did not specify getInitialProps or getStaticProps in the _app.tsx.

Here's how my _app.tsx looks like ```typescript import type { AbstractIntlMessages } from "next-intl"; import type { AppProps } from "next/app"; import { Provider as JotaiProvider } from "jotai"; import { NextIntlProvider } from "next-intl"; import { ThemeProvider } from "next-themes"; import { useRouter } from "next/router"; import nProgress from "nprogress"; import { useEffect } from "react"; import { Footer } from "@/components/Footer"; import { Navigation } from "@/components/Navigation"; import "@/assets/styles/cards.scss"; import "@/assets/styles/main.scss"; import "@/assets/styles/markdown.scss"; import "@/assets/styles/nprogress.scss"; const MyApp = ({ Component, pageProps }: AppProps<{ messages?: AbstractIntlMessages }>) => { const router = useRouter(); useEffect(() => { nProgress.configure({ showSpinner: false, easing: "ease", speed: 250, }); console.log("nProgress configured"); const handleStart = () => { nProgress.start(); }; const handleStop = () => { setTimeout(() => { nProgress.done(); }, 100); }; router.events.on("routeChangeStart", handleStart); router.events.on("routeChangeComplete", handleStop); router.events.on("routeChangeError", handleStop); return () => { router.events.off("routeChangeStart", handleStart); router.events.off("routeChangeComplete", handleStop); router.events.off("routeChangeError", handleStop); }; }, []); return (
); }; export default MyApp; ```
And here's my Footer.tsx (Navigations is just way too big) ```typescript import type { FC } from "react"; import { useTranslations } from "next-intl"; import { ExternalLink } from "@/components/ExternalLink"; import { DiscordLogo } from "@/components/icons/DiscordLogo"; import { GitHubLogo } from "@/components/icons/GitHubLogo"; export const Footer: FC = () => { const t = useTranslations(); return (

{t.rich("footer.affiliation", { officialWebsite: (children) => ( {children} ), })}
{t.rich("footer.copyright", { officialWebsite: (children) => ( {children} ), })}

GitHub

Discord

); }; ```

If I keep Navigation or Footer in here, using next build will produce the errors although the project will be built anyways. To avoid those errors I'd have to remove both Navigation and Footer out of the returned jsx in my _app.tsx.

Hopefully this was somewhat helpful :sweat_smile:

LunarMelody commented 2 years ago

Just a little followup, moving the Navigation and Footer components in Layout.tsx helps and prevents the errors from happening, but it's still kinda weird that it happens in the first place. When the error is being thrown, it's originalMessage is undefined as well which makes it a bit hard to debug. To me, it looks like that you can't really use useTranslations() hook outside of pages context? Otherwise build errors.

amannn commented 2 years ago

Hey @TenkoSpirit and thanks for chiming in!

I think what's probably happening here is this: Next.js creates a 404 page at build time where the _app component is used. Since you're providing messages on a page-level, in case of the 404 page there are no pageProps.messages defined. That means the shared components in _app that render during the build for the 404 page don't have any messages available and therefore the error is caused:

[Error]: MISSING_MESSAGE

The fix is probably to create a custom 404 page where you define getStaticProps and return the messages for the shared component.

Let me know if this helps!

LunarMelody commented 2 years ago

Hello @amannn!

I actually do have a custom 404 page in my project with messages in getStaticProps there, not really sure what else could be causing these errors πŸ˜…

amannn commented 2 years ago

Ah, true! I just checked out your project and found that the errors are caused by the absence of the 500 error page. That page is also generated at build time.

After adding such a page with messages, the warning goes away for me in your project. Let me know if this helps!

Btw. I noticed you migrated away from next-i18next. Recently adoption of next-intl has grown quite a bit and I'm trying to understand where that's coming from. Can I ask if there is something in particular that made you switch and why you picked next-intl then instead?

LunarMelody commented 2 years ago

@amannn oh, alright, will try that a bit later once I get back to my PC!

As for switching away from next-i18next, there are a couple of reasons for me, and the most important one is the lack of hot reloading of translation files during development. I really like the simplicity of next-intl, the fact that the library makes me use native imports/requires is also nice, that contributes a lot to the feeling of having control of what's going on exactly. next-i18next is an amazing solution, but for my project I think it's a little overkill, since I don't really want to deal with caching or fetching from external storages and etc. πŸ˜„

amannn commented 2 years ago

Thanks for the feedback, I'm really glad to hear when next-intl works well for you! πŸ™Œ

Let me know if you run into something else and good luck with your project!

LunarMelody commented 2 years ago

Happy to share that creating a custom 500.tsx did help! Errors don't appear anymore :)

amannn commented 2 years ago

Really cool to hear! πŸ™Œ