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

Using getInitialProps in a simple page #453

Open
VictorAssis opened this issue Jan 18, 2021 · 18 comments
Open

Using getInitialProps in a simple page #453

VictorAssis opened this issue Jan 18, 2021 · 18 comments
Labels
bug Something isn't working
Milestone

Comments

@VictorAssis
Copy link

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.

@aralroca
Copy link
Owner

aralroca commented Jan 18, 2021

@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.

@VictorAssis
Copy link
Author

@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.

@aralroca
Copy link
Owner

@VictorAssis it looks related to this issue: #444

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

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 aralroca added the bug Something isn't working label Jan 18, 2021
@aralroca aralroca added this to the 1.0.2 milestone Jan 18, 2021
@coderjib
Copy link

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

@aralroca
Copy link
Owner

@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 aralroca modified the milestones: 1.0.2, 1.0.3 Jan 29, 2021
@greyarch
Copy link

This is still happening on 1.0.2-canary.9

@greyarch
Copy link

My workaround is to add this:

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

@gorkalaucirica
Copy link

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.

@theoludwig
Copy link
Contributor

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.

@aralroca
Copy link
Owner

This will be fixed after this PR in Next.js vercel/next.js#21930

@aralroca aralroca modified the milestones: 1.0.3, 1.0.4 Feb 23, 2021
@aralroca aralroca modified the milestones: 1.0.5, 1.0.6 Mar 22, 2021
@aralroca aralroca modified the milestones: 1.0.6, 1.0.7 Apr 22, 2021
@aralroca
Copy link
Owner

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

@gorkalaucirica
Copy link

gorkalaucirica commented May 11, 2021

I'm still getting the same error:

$ yarn list | grep next@
├─ next@10.2.1-canary.4
$ yarn list | grep next-translate
├─ next-translate@1.0.6
$ 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;

@zachguo
Copy link

zachguo commented May 16, 2021

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

@aralroca aralroca modified the milestones: 1.0.7, 1.0.8 May 21, 2021
@gorkalaucirica
Copy link

gorkalaucirica commented May 24, 2021

Warning logs are no longer shown after upgrading to next-translate@1.0.7 🎉 :

$ yarn list | grep next@
├─ next@10.2.2
$ yarn list | grep next-translate
├─ next-translate@1.0.7
$ 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

@aralroca aralroca modified the milestones: 1.1.0, future Sep 18, 2021
@ajmnz
Copy link
Contributor

ajmnz commented Oct 27, 2021

@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

@aralroca
Copy link
Owner

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

@mattvb91
Copy link

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

@BjoernRave
Copy link
Contributor

BjoernRave commented Apr 28, 2023

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
None yet
Development

No branches or pull requests

10 participants