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鈥檒l occasionally send you account related emails.

Already on GitHub? Sign in to your account

[examples] SSR on the Next.js official example not working #32051

Closed
2 tasks done
ziedHamdi opened this issue Mar 30, 2022 · 34 comments
Closed
2 tasks done

[examples] SSR on the Next.js official example not working #32051

ziedHamdi opened this issue Mar 30, 2022 · 34 comments
Assignees
Labels
examples Relating to /examples status: waiting for author Issue with insufficient information

Comments

@ziedHamdi
Copy link

Duplicates

  • I have searched the existing issues

Latest version

  • I have tested the latest version

Current behavior 馃槸

Cloning the official next.js ssr example is not doing ssr at all:

Disabling javascript in the browser shows a raw html page (with almost no css except those for fonts)

Expected behavior 馃

Expected to see the page styled

Steps to reproduce 馃暪

Steps:

1.curl https://codeload.github.com/mui/material-ui/tar.gz/master | tar -xz --strip=2 material-ui-master/examples/nextjs
2.cd nextjs
3.yarn install
4.yarn dev
5.disabled javascript in browser
6.load localhost:3000

Context 馃敠

This is related to me migrating my project from v4 to v5. Here's the StackOverflow question related to this bug

Your environment 馃寧

`npx @mui/envinfo`
  Don't forget to mention which browser you used.
  Output from `npx @mui/envinfo` goes here.
  System:
    OS: Linux 5.13 Ubuntu 20.04.4 LTS (Focal Fossa)
  Binaries:
    Node: 16.14.2 - /usr/bin/node
    Yarn: 1.22.18 - /usr/bin/yarn
    npm: 8.5.0 - /usr/bin/npm
  Browsers:
    Chrome: 99.0.4844.74
    Firefox: 98.0.2
  npmPackages:
    @emotion/react: latest => 11.8.2 
    @emotion/styled: latest => 11.8.1 
    @mui/base:  5.0.0-alpha.74 
    @mui/icons-material: latest => 5.5.1 
    @mui/material: latest => 5.5.3 
    @mui/private-theming:  5.5.3 
    @mui/styled-engine:  5.5.2 
    @mui/system:  5.5.3 
    @mui/types:  7.1.3 
    @mui/utils:  5.5.3 
    @types/react:  17.0.43 
    react: latest => 18.0.0 
    react-dom: latest => 18.0.0 

I'm using chrome

@ziedHamdi ziedHamdi added the status: waiting for maintainer These issues haven't been looked at yet by a maintainer label Mar 30, 2022
@ziedHamdi
Copy link
Author

Capture d鈥櫭ヽran de 2022-03-30 09-25-46

@danilo-leal danilo-leal changed the title SSR with next.js official example doesn't work [examples] SSR on the Next.js official example not working Mar 30, 2022
@danilo-leal danilo-leal added the examples Relating to /examples label Mar 30, 2022
@igordanchenko
Copy link
Contributor

@ziedHamdi apparently something is not playing nice with React 18 here (React 18 was released literally 1 day ago)

You can resolve this issue by downgrading to React 17 in your package.json:

    "react": "^17.0.2",
    "react-dom": "^17.0.2"

@mnajdova
Copy link
Member

We probably want to update the react version in the examples until we are fully compatible with React 18

@ziedHamdi
Copy link
Author

ziedHamdi commented Mar 31, 2022

@igordanchenko thanks for the fast reply, I'm happy that it's actually just a React 18 problem for the example.

I'd be interested in how you will find the problem in React 18:

Because I have React 17.0.2 in my project and that's where I noticed SSR was not working anymore after migrating to mui5. StackOverflow original problem

I really don't know where to look, as I don't know what is expected to be returned by extractCriticalToChunks (kind of a black box to me)? Do I have to enable a debug mode for emotion to understand what went wrong etc...

I also don't know how to create a project that reproduces the bug, since I don't know at which moment my project (with all its intricate complexities) will stop working if I start from your template and keep adding stuff.

Are there any documents you could recommend for that? Or should I wait until you fix the React 18 issue and check if it was solved?

@ziedHamdi
Copy link
Author

ziedHamdi commented Mar 31, 2022

I reproduced a 'non working' ssr version even in React 17.0.2 by starting with your working project and editing index.js in a more real world project like form

https://github.com/ziedHamdi/mui-next-ssr-error

I'd be glad to help find out what's going wrong, I just don't know where to start, so please do not hesitate to tell me if I can help somehow

@mnajdova
Copy link
Member

mnajdova commented Apr 4, 2022

I don't understand what is not working, this is what I am seeing:

image

With both enabled/disabled JavaScript in order to test SSR.

@mnajdova mnajdova added status: waiting for author Issue with insufficient information and removed status: waiting for maintainer These issues haven't been looked at yet by a maintainer labels Apr 4, 2022
@ziedHamdi
Copy link
Author

ziedHamdi commented Apr 5, 2022 via email

@mnajdova
Copy link
Member

mnajdova commented Apr 5, 2022

I just saw that you also use makeStyles which is the legacy styling solution that depends on JSS. This should be the root of the problem. Note that if you wish to still use makeStyles, you need to configure JSS for SSR too.

For example, have a look how we are doing it on our documentation

You will need to have configured both emotion and JSS. I would strongly recommend using sx and styled() with @mui/material to avoid bundling two styling packages and additional issues like this one.

@ziedHamdi
Copy link
Author

ziedHamdi commented Apr 11, 2022

Hi @mnajdova ,

I just removed makeStyle (from tss-react as described in your migration guide) and things seem to work back.

There remains one issue with useMediaQuery that is not reacting when js is disabled. You can see it in the app: there's a text saying 'large screen content' that you can see on large screens if js is enabled but that disappears otherwise.

Also in my app, I have nothing that works, I'll try to move files progressively to this project to understand when it stops working and get back to you with the cause, that might help other people
Capture d鈥櫭ヽran de 2022-04-11 11-41-05

@ziedHamdi
Copy link
Author

ziedHamdi commented Apr 11, 2022

Cool! I know what was causing the problem: it's the StyledEngineProvider, you can check the last commit to see how it brakes the ssr
Capture d鈥櫭ヽran de 2022-04-11 11-40-39

@mnajdova
Copy link
Member

@ziedHamdi did you follow the instruction for setting up SSR from the tss-react repo?

@ziedHamdi
Copy link
Author

Sure! I double-checked. You can still see it in the git history of the project.

@garronej
Copy link
Contributor

garronej commented Apr 17, 2022

I confirm that react 18 break SSR for us.
Still investigating.

@garronej
Copy link
Contributor

garronej commented Apr 18, 2022

Hi @mnajdova,
I got an issue reporting SSR no longer working with Next and React 18. I started investigating only to find out the problem is much bigger than I thought and affect MUI as a whole.
I opened an issue on the emotion repo.
I feel the situation is bigger than me. I let you find a solution and will update tss-react accordingly.

Best regards,

@Andarist
Copy link
Contributor

@garronej has prepared a good repro case and based on it I've created an issue in Next.js project to clarify how this is supposed to be set up: vercel/next.js#36268

@Andarist
Copy link
Contributor

The created issue was closed by this PR so I assume that this should get fixed with the next Next release.

@prisis
Copy link

prisis commented Apr 24, 2022

I did try the latest nextjs 12.1.6-canary.6 release and i have still the issue.

If you trying extending the theme, the component can't read a custom key that you add to the theme.

Example:

import { createTheme as createBaseTheme, responsiveFontSizes } from "@mui/material";

const createTheme: (themeMode: "light" | "dark", themeDirection: Direction, responsiveFont?: boolean) => ITheme = (
    themeMode,
    themeDirection,
    responsiveFont = true,
) => {
    const isLight = themeMode === "light";

    const themeOptions = useMemo(() => {
        return {
            direction: themeDirection,
            customShadows: {
                z24: "0  0 4px 0 1, 0 24px 48px 0 1",
                z20: "0  0 4px 0 1, 0 24px 48px 0 1",
            },
            customComponent: {},
        };
    }, [isLight, themeDirection]);

    const theme = createBaseTheme(themeOptions) as unknown as ITheme;

    if (responsiveFont) {
        return responsiveFontSizes(theme);
    }

    return theme;
};

Than the customShadows cannot be found in a component which is using the key

@Andarist
Copy link
Contributor

Please prepare a full runnable repro case so I could jump into investigating this

@github-actions
Copy link

github-actions bot commented May 3, 2022

Since the issue is missing key information, and has been inactive for 7 days, it has been automatically closed.
If you wish to see the issue reopened, please provide the missing information.

@github-actions github-actions bot closed this as completed May 3, 2022
@garronej
Copy link
Contributor

garronej commented May 3, 2022

Hi,
Next 12.1.6 just released.
I confirm that it solves the root issue.

@prisis
Copy link

prisis commented May 4, 2022

The error is still there, with custom themes

@garronej
Copy link
Contributor

garronej commented May 4, 2022

this issue is fixed.
SSR is still broken but @prisis your problem is unrelated and it's:

https://github.com/prisis/broken-ssr/blob/cfc06066f1c2e3331424e8fe83169ba240dc00a8/pages/index.tsx#L10

-const CustomButton = styled(Button, {})((theme) => {
+const CustomButton = styled(Button, {})(({ theme} ) => {

If you want to declare custom key in theme and have it working with typescript you have to implement module augmentation, example here

Also I point out that this memoization is unessesary, you create a new theme each render anyway:
https://github.com/prisis/broken-ssr/blob/cfc06066f1c2e3331424e8fe83169ba240dc00a8/shared/theme.tsx#L33-L41

And here it should be useCreateTheme (I advise to favor named export to avoid such kind of error):
https://github.com/prisis/broken-ssr/blob/cfc06066f1c2e3331424e8fe83169ba240dc00a8/pages/_app.tsx#L20

@garronej
Copy link
Contributor

garronej commented May 6, 2022

UPDATE:

It's still broken, but for another reason. This is solved, now it's this.

@mnajdova I think this should be reopened until Versel fixes the regression.

Best regards

@prisis
Copy link

prisis commented May 7, 2022

Offtopic:

@garronej good that you updated your comment, next time think twice how you write a message.

Thanks for the hint.

@mhamendes
Copy link

Just experienced a similar error in my project. The html built in server-side didn't have any css and turns out it was because I updated Next to version 12.1.6. Once I downgraded it back to version 12.1.4 everything went back to normal.

Using next@12.1.4, react@^18.1.0, react-dom@^18.1.0, mui/material@^5.8.0 and mui/material-icons@^5.8.0 everything works fine here.

@garronej
Copy link
Contributor

Hooray it works with Next 12.1.7-canary.4 馃コ

@ziedHamdi
Copy link
Author

ziedHamdi commented May 23, 2022

I don't know if it is related to this bug, but I have some styles that do not appear in SSR. Even an id of a Box doesn't appear in SSR but appears when run client side. The screen captures here can be tested at my website here. Open developer mode and choose mobile view with 310px width. The first load will be css broken, then close
the protest detail (next to the logo), and reopen it (second image at home page) and everything will work fine.

PLEASE NOTICE EVEN THE DIV ID IS NOT PRESENT IN SSR

In SSR even id is not rendered
When navigating through the app, things work as expected

My code is pretty forward: detail.js returns this

        <MainLayout>
            <Head>
                <title>{props.meta.title}</title>
                <meta name="description" content={props.meta.seoDesc}/>
                <meta name="title" property="og:title" content={props.meta.title}/>
                <meta name="description" property="og:description" content={props.meta.desc}/>
                <meta name="image" property="og:image" content={props.meta.img}/>
                <meta property="og:type" content="article"/>
                <meta property="og:url" content={props.fullUrl}/>
                <meta property="og:locale" content="en_US"/>
            </Head>
            <IssueDetail issueId={issueId}/>
        </MainLayout>

And IssueDetail is as follows:

import {Box, Grid, Paper, useMediaQuery} from "@mui/material";
import {useTranslation} from "next-i18next";
import React, {useEffect, useState} from "react";
import {useSession} from "next-auth/react";
import {useQuery} from "@apollo/client";
import {COMPLAINT} from "../../constants/graphQueries";
import DisplayState, {DEFAULT_STATES} from "../common/DisplayState";
import IssuePanel from "./IssuePanel";
import EntityInfo from "../entity/EntityInfo";
import CommentList from "./actions/CommentList";
import useToast from "../../common/transverse/toast/hook/useToast";
import {TOAST_TIMEOUT} from "../../constants/screenSizes";

const sx = {
    IssueDetail: {
        display: 'flex',
        flexDirection: 'row',
        flexWrap: 'nowrap',
        gap: 2,
        p: {
            xs: 0,
            md: 2
        }
    },
    leftPanel: {
        flexBasis: {
          xs: '100%',
          md: '75%'
        },
        flexGrow: 1,
        maxWidth: '100%'
    },
    rightPanel: {
        flexGrow: 0,
        flexBasis: {
            md: '25%'
        },
        maxWidth: '25%'
    },
    issueContent: {
        p:2
    },
    commentListPanel: {
        px: 2,
        py: 0,
        flexDirection: 'column',
        gap: 1
    }
}

export function constructTitle(issue) {
    return (issue?.entity?.name ?? "") + ": " + (issue?.title ?? "");
}

export default function IssueDetail(props) {
    const [issue, setIssue] = useState()
    const { data: session, status } = useSession()
    const {t} = useTranslation('complaintList')
    const {issueId} = props
    const largerScreen = useMediaQuery(theme => theme.breakpoints.up('md'))

    const {addToast} = useToast(TOAST_TIMEOUT)
    const {loading, data, error} = useQuery(COMPLAINT, {
        variables: {issueId},
        onCompleted: onIssueLoaded,
        onError: (error)=> addToast({message:error.message})
    })

    useEffect(() => {
            document.title = constructTitle(issue)
        }, [issue?.title]
    )

    if (error)
        return <DisplayState state={DEFAULT_STATES.ERROR} message={error.message} error={error}/>

    if (loading || !issue)
        return <DisplayState state={DEFAULT_STATES.LOADING}/>

    return (
        <Box sx={sx.IssueDetail} id="IssueDetail">
            <Box sx={sx.leftPanel}>
                <Paper>
                    <IssuePanel issue={issue} contentSx={sx.issueContent}/>
                    <CommentList issue={issue} sxClass={sx.commentListPanel}/>
                </Paper>
            </Box>

            {largerScreen && <Box sx={sx.rightPanel}>
                <EntityInfo entityPartial={issue.entity}/>
            </Box>}

        </Box>

    )

    function onIssueLoaded(data) {
        if (data) {
            setIssue(data.complaintById)
        }
    }

}

@Andarist
Copy link
Contributor

@ziedHamdi it's super hard to tell what might be wrong based on just a code. Ideally you should provide a minimal runnable repro case of the problem and share that with maintainers so they could take a look at this.

@ziedHamdi
Copy link
Author

I know @Andarist, I'm the one who started this issue (with an example) :-).

This post was just in case someone had the same issue to react here. As you can imagine, the project is complex, and some css work correctly and some other not. Finding when this occurs exactly is not easy and takes time. So I was hoping someone had this on a less complex codebase.

@Andarist
Copy link
Contributor

You could try bisecting your codebase - remove stuff in huge chunks and observe if the issue is still reproducible. This usually helps narrow cases like this relatively quickly.

@ziedHamdi
Copy link
Author

Ok I'll try to do that and file another issue with the repo

@sahanaravi
Copy link

Was this resolved? I have the exact same issue

@sahanaravi
Copy link

OK, so in your repo, you have both CacheProvider and StyledEngineProvider. You need only CacheProvider and that will resolve the issue

@rahulcn
Copy link

rahulcn commented Feb 7, 2023

Complete the v5 migration with tss-react, it worked for me.
https://mui.com/material-ui/migration/migrating-from-jss/#2-use-tss-react
https://docs.tss-react.dev/ssr/next.js#mui-and-tss-use-different-caches

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
examples Relating to /examples status: waiting for author Issue with insufficient information
Projects
None yet
Development

No branches or pull requests

10 participants