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

Errors/Warnings during build #87

Closed
silvestreh opened this issue Feb 15, 2022 · 11 comments
Closed

Errors/Warnings during build #87

silvestreh opened this issue Feb 15, 2022 · 11 comments

Comments

@silvestreh
Copy link

silvestreh commented Feb 15, 2022

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
Copy link
Owner

amannn commented Feb 15, 2022

Hi and thanks for the report!

There was a similar error reported in #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
Copy link
Owner

amannn commented Mar 9, 2022

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

@amannn amannn closed this as completed Mar 9, 2022
@LunarMelody
Copy link

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
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 (
    <NextIntlProvider messages={pageProps.messages}>
      <JotaiProvider>
        <ThemeProvider attribute="class">
          <div className="app-container mx-auto max-w-screen-2xl gap-4 px-2">
            <Navigation />
            <Component {...pageProps} />
            <Footer />
          </div>
        </ThemeProvider>
      </JotaiProvider>
    </NextIntlProvider>
  );
};

export default MyApp;
And here's my Footer.tsx (Navigations is just way too big)
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 (
    <footer className="footer grid grid-cols-1 grid-rows-[auto_auto] border-t py-6 px-4 text-sm text-gray-400 lg:grid-cols-[1fr_auto] lg:grid-rows-1">
      <p>
        {t.rich("footer.affiliation", {
          officialWebsite: (children) => (
            <ExternalLink href="https://www.mihoyo.com/">{children}</ExternalLink>
          ),
        })}
        <br />
        {t.rich("footer.copyright", {
          officialWebsite: (children) => (
            <ExternalLink href="https://www.mihoyo.com/">{children}</ExternalLink>
          ),
        })}
      </p>

      <div className="mt-6 flex flex-col gap-x-6 gap-y-2 place-self-start font-bold lg:mt-0 lg:flex-row lg:place-self-center">
        <ExternalLink href="https://github.com/kitsune-guuji/gvp">
          <div className="flex flex-row items-center gap-x-2">
            <GitHubLogo className="inline-block h-auto w-4" />
            <p>GitHub</p>
          </div>
        </ExternalLink>

        <ExternalLink href="https://discord.gg/[REDACTED]">
          <div className="flex flex-row items-center gap-x-2">
            <DiscordLogo className="inline-block h-auto w-4" />
            <p>Discord</p>
          </div>
        </ExternalLink>
      </div>
    </footer>
  );
};

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 😅

@LunarMelody
Copy link

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
Copy link
Owner

amannn commented Sep 12, 2022

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
Copy link

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
Copy link
Owner

amannn commented Sep 12, 2022

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
Copy link

@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
Copy link
Owner

amannn commented Sep 12, 2022

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
Copy link

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

@amannn
Copy link
Owner

amannn commented Sep 12, 2022

Really cool to hear! 🙌

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

No branches or pull requests

3 participants