next-translate icon indicating copy to clipboard operation
next-translate copied to clipboard

Using getInitialProps in a simple page

Open VictorAssis opened this issue 4 years ago • 18 comments

I created a POC with apollo and next-translate before implement in my real project, but when run yarn build I am receiving the warning:

🚨 [next-translate] In Next 10.x.x there is an issue related to i18n and getInitialProps. We recommend to replace getInitialProps to getServerSideProps on /about.js. Issue: https://github.com/vercel/next.js/issues/18396

But the about page has basically just HTML. Has a way to know why next-translate is detecting getInitialProps?

I created this repository with the code to reproduce the error: https://github.com/VictorAssis/next-translate-bug

The folder apollo has the sample without next-translate. Below is the result of yarn build in this folder:

$ yarn build
yarn run v1.22.10
$ next build
info  - Creating an optimized production build  
info  - Compiled successfully
info  - Collecting page data  
info  - Generating static pages (5/5)
info  - Finalizing page optimization  

Page                                                           Size     First Load JS
┌ ● / (ISR: 1 Seconds)                                         2.46 kB         118 kB
├   /_app                                                      0 B             111 kB
├ ○ /404                                                       3.03 kB         114 kB
├ ○ /about                                                     1.54 kB         117 kB
├ ○ /client-only                                               2.58 kB         118 kB
└ ○ /mutation-only                                             1.48 kB         117 kB
+ First Load JS shared by all                                  111 kB
  ├ chunks/7a4ec7434064424e60603514b1a9c05d0a274b85.5bc5b7.js  44.6 kB
  ├ chunks/commons.7af247.js                                   13.1 kB
  ├ chunks/framework.d2ae40.js                                 39.9 kB
  ├ chunks/main.5f1b34.js                                      6.62 kB
  ├ chunks/pages/_app.d001ab.js                                5.94 kB
  └ chunks/webpack.50bee0.js                                   751 B

λ  (Server)  server-side renders at runtime (uses getInitialProps or getServerSideProps)
○  (Static)  automatically rendered as static HTML (uses no initial props)
●  (SSG)     automatically generated as static HTML + JSON (uses getStaticProps)
   (ISR)     incremental static regeneration (uses revalidate in getStaticProps)

Done in 11.50s.

The folder apollo-with-translate has the sample with next-translate. Below is the result of yarn build in this folder:

$ yarn build
yarn run v1.22.10
$ next build
🚨 [next-translate] In Next 10.x.x there is an issue related to i18n and getInitialProps. We recommend to replace getInitialProps to getServerSideProps on /about.js. Issue: https://github.com/vercel/next.js/issues/18396
🚨 [next-translate] In Next 10.x.x there is an issue related to i18n and getInitialProps. We recommend to replace getInitialProps to getServerSideProps on /about.js. Issue: https://github.com/vercel/next.js/issues/18396
info  - Creating an optimized production build  
info  - Compiled successfully
info  - Collecting page data  
[   =] info  - Generating static pages (0/13)next-translate - compiled page: /client-only - locale: en - namespaces: common - used loader: getStaticProps
[    ] info  - Generating static pages (0/13)next-translate - compiled page: /client-only - locale: pt - namespaces: common - used loader: getStaticProps
next-translate - compiled page: /client-only - locale: es - namespaces: common - used loader: getStaticProps
[   =] info  - Generating static pages (0/13)next-translate - compiled page: /mutation-only - locale: en - namespaces: common - used loader: getStaticProps
[  ==] info  - Generating static pages (0/13)next-translate - compiled page: /mutation-only - locale: pt - namespaces: common - used loader: getStaticProps
next-translate - compiled page: /mutation-only - locale: es - namespaces: common - used loader: getStaticProps
[=== ] info  - Generating static pages (6/13)next-translate - compiled page: / - locale: en - namespaces: common - used loader: getStaticProps
[  ==] info  - Generating static pages (9/13)next-translate - compiled page: / - locale: es - namespaces: common - used loader: getStaticProps
[==  ] info  - Generating static pages (9/13)next-translate - compiled page: / - locale: pt - namespaces: common - used loader: getStaticProps
info  - Generating static pages (13/13)
info  - Finalizing page optimization  

Page                                                           Size     First Load JS
┌ ● / (ISR: 1 Seconds)                                         2.46 kB         123 kB
├   /_app                                                      0 B             116 kB
├ ○ /404                                                       3.03 kB         119 kB
├ λ /about                                                     1.88 kB         123 kB
├ ● /client-only                                               2.6 kB          123 kB
└ ● /mutation-only                                             1.79 kB         123 kB
+ First Load JS shared by all                                  116 kB
  ├ chunks/7a4ec7434064424e60603514b1a9c05d0a274b85.6d4571.js  44.6 kB
  ├ chunks/8767b6ece666ce09c9ff0f3e4f19bcb696f59f7d.b128c1.js  3.63 kB
  ├ chunks/commons.66ee68.js                                   13.7 kB
  ├ chunks/framework.d2ae40.js                                 39.9 kB
  ├ chunks/main.28d517.js                                      6.76 kB
  ├ chunks/pages/_app.dbb8a6.js                                6.2 kB
  └ chunks/webpack.0dc619.js                                   1.23 kB

λ  (Server)  server-side renders at runtime (uses getInitialProps or getServerSideProps)
○  (Static)  automatically rendered as static HTML (uses no initial props)
●  (SSG)     automatically generated as static HTML + JSON (uses getStaticProps)
   (ISR)     incremental static regeneration (uses revalidate in getStaticProps)

Done in 12.19s.

My node version is v12.20.1.

VictorAssis avatar Jan 18 '21 17:01 VictorAssis

@VictorAssis Are you using a HoC on the /about.js page? Next-translate uses getInitialProps as default to load the translations when there is a HoC detected (to avoid problems). https://github.com/vinissimus/next-translate/tree/1.0.1#how-are-translations-loaded

You can just write an empty getStaticProps or the method you want to force to avoid the default one.

aralroca avatar Jan 18 '21 18:01 aralroca

@aralroca I'm not using HoC on the about.js (https://github.com/VictorAssis/next-translate-bug/blob/main/apollo-with-translate/pages/about.js) or in the _app.js (https://github.com/VictorAssis/next-translate-bug/blob/main/apollo-with-translate/pages/_app.js).

I tried to add a empty getStaticProps (returning nothing or a empty props) on the page, but i receive the same warning and the error:

> Build error occurred
Error: You can not use getInitialProps with getStaticProps. To use SSG, please remove your getInitialProps
    at Object.isPageStatic (/home/victorassis/Workspace/co3d/with-apollo-app/apollo-with-translate/node_modules/next/dist/build/utils.js:25:46)
    at processTicksAndRejections (internal/process/task_queues.js:97:5) {
  type: 'Error'
}
error Command failed with exit code 1.

VictorAssis avatar Jan 18 '21 19:01 VictorAssis

@VictorAssis it looks related to this issue: https://github.com/vinissimus/next-translate/issues/444

Is detecting the word getInitialProps of /about.js file.. This is because the getInitialProps detection is quite poor:

  • https://github.com/vinissimus/next-translate/blob/1.0.1/src/plugin/loader.ts#L85

Naturally, this needs to be improved and that's why I created the other issue. Improving the detection will fix this. Thanks for reporting the issue.

As a workaround, meanwhile, you can use string concatenation, something like {"getInitial"+"Props"}. Sorry for the inconvenience.

aralroca avatar Jan 18 '21 19:01 aralroca

Hello, thanks for your work. We're seeing this issue even in pages not using the word getInitialProps at all. When doing export default PageName the isWrapperWithExternalHOC function seems to always search for that word "PageName" and successfully matches with the Regex ref. So isWrapperWithExternalHOC always returns true, at least for my Home Page. The only workaround that for me seemed to work is to switch to a direct export, like this: export default () => { // page code } For what I could test, I think the error is in the last couple of lines in utils.ts and in particular in the RegEx matching. Hope this helps

coderjib avatar Jan 19 '21 17:01 coderjib

@VictorAssis @CleverUpEng we did some improvements on the internal hasHOC helper. Is it already happening to you on 1.0.2-canary.9? Thanks 🙏

aralroca avatar Jan 29 '21 15:01 aralroca

This is still happening on 1.0.2-canary.9

greyarch avatar Jan 30 '21 13:01 greyarch

My workaround is to add this:

export function getServerSideProps() { return { props: {} }; }

greyarch avatar Jan 30 '21 14:01 greyarch

Maybe not 100% related to this topic but I encountered some hasHoc related issues also using TypeScript with next-translate v1.0.2. Given the following page:

const Page: React.FC = () => <>OK</>;

export default Page;

You also get:

🚨 [next-translate] In Next 10.x.x there is an issue related to i18n and getInitialProps. We recommend to replace getInitialProps to getServerSideProps on /page.tsx. Issue: https://github.com/vercel/next.js/issues/18396

The workaround is the same mentioned in the comment above.

gorkalaucirica avatar Feb 04 '21 15:02 gorkalaucirica

I can confirm that I also encountered issues while using TypeScript React.FC, but I think I have a better "workaround", by using getServerSideProps, you're losing the performance that calculations are done in build time instead of request time so instead, it's better to use getStaticProps :

export const getStaticProps: GetStaticProps = async () => {
  return { props: {} }
}

Obviously, it would be better to fix this bug, so we can avoid using this workaround, at least it is working.

theoludwig avatar Feb 08 '21 16:02 theoludwig

This will be fixed after this PR in Next.js https://github.com/vercel/next.js/pull/21930

aralroca avatar Feb 12 '21 18:02 aralroca

Should be fixed in Next.js canary 10.2.1-canary.4 Can someone confirm it?

aralroca avatar May 10 '21 20:05 aralroca

I'm still getting the same error:

$ yarn list | grep next@
├─ [email protected]
$ yarn list | grep next-translate
├─ [email protected]
$ yarn dev
yarn run v1.22.10
info  - Using webpack 4. Reason: custom webpack configuration in next.config.js https://nextjs.org/docs/messages/webpack5
info  - Using external babel configuration from /Users/gorkalaucirica/Development/Libere/web/.babelrc
event - compiled successfully
event - build page: /404
wait  - compiling...
🚨 [next-translate] In Next 10.x.x there is an issue related to i18n and getInitialProps. We recommend to replace getInitialProps to getServerSideProps on /404.tsx. Issue: https://github.com/vercel/next.js/issues/18396
🚨 [next-translate] In Next 10.x.x there is an issue related to i18n and getInitialProps. We recommend to replace getInitialProps to getServerSideProps on /404.tsx. Issue: https://github.com/vercel/next.js/issues/18396
🚨 [next-translate] In Next 10.x.x there is an issue related to i18n and getInitialProps. We recommend to replace getInitialProps to getServerSideProps on /_error.tsx. Issue: https://github.com/vercel/next.js/issues/18396
🚨 [next-translate] In Next 10.x.x there is an issue related to i18n and getInitialProps. We recommend to replace getInitialProps to getServerSideProps on /_error.tsx. Issue: https://github.com/vercel/next.js/issues/18396
event - compiled successfully
Error: `pages/404` can not have getInitialProps/getServerSideProps, https://nextjs.org/docs/messages/404-get-initial-props
    at renderToHTML (/Users/gorkalaucirica/Development/Libere/web/node_modules/next/next-server/server/render.tsx:545:13)
    at fn (/Users/gorkalaucirica/Development/Libere/web/node_modules/next/next-server/server/next-server.ts:1717:32)
    at doRender (/Users/gorkalaucirica/Development/Libere/web/node_modules/next/next-server/server/next-server.ts:1643:31)
    at DevServer.renderToHTMLWithComponents (/Users/gorkalaucirica/Development/Libere/web/node_modules/next/next-server/server/next-server.ts:1817:15)
    at DevServer.renderErrorToHTML (/Users/gorkalaucirica/Development/Libere/web/node_modules/next/next-server/server/next-server.ts:2039:27)
    at runMicrotasks (<anonymous>)
    at processTicksAndRejections (node:internal/process/task_queues:94:5)
    at DevServer.renderErrorToHTML (/Users/gorkalaucirica/Development/Libere/web/node_modules/next/server/next-dev-server.ts:680:19)
    at DevServer.renderError (/Users/gorkalaucirica/Development/Libere/web/node_modules/next/next-server/server/next-server.ts:1979:18)

The 404 page:

import Error from "./_error";

const Error404: React.FC = () => {
  return (
    <>
      <Error statusCode={404} />
    </>
  );
};

export default Error404;

gorkalaucirica avatar May 11 '21 06:05 gorkalaucirica

next-translate had an issue of not translating HOC wrapped pages, v10.2.1-canary.4 does fix the issue.

zachguo avatar May 16 '21 23:05 zachguo

Warning logs are no longer shown after upgrading to [email protected] 🎉 :

$ yarn list | grep next@
├─ [email protected]
$ yarn list | grep next-translate
├─ [email protected]
$ yarn dev
event - compiled successfully

Error: pages/404 can not have getInitialProps/getServerSideProps reported in the comment above is related to #491, so this issue seems fixed

gorkalaucirica avatar May 24 '21 08:05 gorkalaucirica

@aralroca 👋

I'm still having a similar issue on the 404 page (next-translate v1.1.0)

Error: `pages/404` can not have getInitialProps/getServerSideProps, https://nextjs.org/docs/messages/404-get-initial-props

This is my 404.tsx

import React from "react";
import { useTypeSafeTranslation } from "../hooks/useTypeSafeTranslation";

interface NotFoundPageProps {}

const NotFoundPage: React.FC<NotFoundPageProps> = () => {
  const { t } = useTypeSafeTranslation("common");

  return <div>{t("404.notFound")}</div>;
};

export default NotFoundPage;

A dirty workaround is just to export an empty getStaticProps, but would love to get it to work without having to do so.

export const getStaticProps: GetStaticProps = async () => {
  return {
    props: {},
  };
};

btw, useTypeSafeTranslation is just a typesafe useTranslation

ajmnz avatar Oct 27 '21 22:10 ajmnz

This should be solved in https://github.com/aralroca/next-translate/releases/tag/2.0.0-experimental.2 do you can confirm? Thanks for your feedback

aralroca avatar Oct 19 '22 18:10 aralroca

Hi, is there a sample of this working with getInitialProps?

mattvb91 avatar Apr 23 '23 13:04 mattvb91

I still experience this problem. The only route /problem is the only one I don't wrap with a ContextProvider. I have the following code in _app.tsx :

function MyApp(props: AppProps) {
  const { Component, pageProps } = props
  const [queryClient] = useState(() => new QueryClient())

  useAdjustedViewport()

  return (
    <QueryClientProvider client={queryClient}>
      <Hydrate state={pageProps.dehydratedState}>
        <Toaster />
        {/* <CookieBanner /> */}
        <AuthContextProvider>
          <Component {...pageProps} />
        </AuthContextProvider>
      </Hydrate>
    </QueryClientProvider>
  )
}

export default MyApp

And the AuthContextProvider looks like this:

if (pathname === '/problem') {
    return <>{children}</>
  }

  if (user === null || !event) {
    return <PageLoader />
  }

  return (
    <AuthContext.Provider
      value={{
        placedOrders: placedOrders,
        activeOrder: orders?.find((order) =>
          [
            'NEW',
            'PLACED',
            'PARTIALLY_READY',
            'PAYMENT_PENDING',
            'PREPARING',
          ].includes(order.status)
        ),
        sidebarOpen,
        hideCart,
        setHideCart,
        setSidebarOpen,
        apiMode,
        user,
        setUser,
        baseUrl,
        setTable,
        setApiMode,
        group,
        refetchGroup,
        event,
        table,
        refetchOrders,
      }}>
      {children}
      {cartPages.includes(pathname) && !hideCart && <SmallCart />}
      <JoinGroupSheet
        isOpen={isRequestingName}
        onClose={() => {
          setIsRequestingName(false)

          const newQuery = { ...query }

          delete newQuery.join_code

          push({
            pathname: pathname,
            query: newQuery,
          })
        }}
      />
      {isCheckingIn && (
        <VenueCheckinSheet
          isOpen={isCheckingIn}
          onClose={() => setIsCheckingIn(false)}
        />
      )}
    </AuthContext.Provider>
  )

This is probably related. In the whole app I am neither using getInitialProps, getStaticProps or getServerSideProps

next-translate(-plugin): 2.0.5 next: 13.3.1

Screenshot 2023-04-28 at 19 27 06

BjoernRave avatar Apr 28 '23 17:04 BjoernRave