Although our Next.js project used server-side rendering (SSR), SEO meta tags were not appearing correctly for search engines. SEO was broadly broken on key pages, including product details and the Expert home page. Investigating revealed several intertwined layers: the combination of AuthProvider and NextSeo, useMediaQuery compatibility with SSR, and the SEO component’s useState/useEffect implementation.
This post walks through the approaches I tried and the eventual solution, step by step. I hope it helps developers implementing both SSR and SEO in Next.js.
TL;DR
The problem
- SEO across the marketplace, including product details and the Expert home page, was broken.
- Server-side rendering did not work under AuthProvider; components ran only on the client. We use an SEO library called NextSeo. However, the NextSeo component did not render under AuthProvider.
Attempted solutions
- Changed AuthProvider so its children could render before initialization finished, rather than waiting for initialization.
- Fetched authentication information through getInitialProps.
- Needed to work out the details of handling useMediaQuery, which runs only on the client, when rendering the global navigation bar (GNB). Temporarily fixed the GNB area’s height.
- Changed the shared SEO component to apply props directly instead of managing metadata with useState.
Issue 1. AuthStore and GNB Rendering
- Return children under authStore, rendering only the GNB after initialization.
return !isInitializing ? (
<ReactChannelIO
pluginKey={CHANNEL_ID_PLUGIN_KEY}
language="ko"
autoBoot={CHANNEL_USE_AUTO_BOOT}
{...(isLoggedIn &&
user?.id && {
memberId: `${user.id}`,
profile: { name: user.displayName },
})}>
{children}
</ReactChannelIO>
) : (
<>{children}</> //as-is null
)
})
- Problem: login information was checked on the client, causing a state-related reflow in the GNB.
- Render only the GNB after initialization.
<WebViewWrapper>
{!isInitializing && isUseFooter && renderGNB}
<Content>{children}</Content>
{isUseFooter && <FooterView />}
</WebViewWrapper>
- Problem: reflow occurred in the GNB.
- Fix the size of the GNB area to improve reflow.
- Problem: reflow improved, but the rendering delay relative to the content below remained..
- Then wait for initialization for the whole component? The entire page looks like a cold start. And does using Next.js even make sense then..?
- Let’s fetch user information on the server.
MyApp.getInitialProps = async (appContext) => {
// calls page's `getInitialProps` and fills `appProps.pageProps`
const appProps = await App.getInitialProps(appContext)
const req = appContext.ctx.req
let auth = req?.auth
let { cookie } = appContext.ctx.req.headers
let accessToken = cookie.split(';').find((c) => c.trim().startsWith('accessToken'))
if (accessToken) {
accessToken = accessToken.split('=')[1]
try {
let response = await getMe(accessToken)
auth = { ...auth, ...response }
} catch (e) {}
}
return { ...appProps, auth: auth }
}
Fixed..!
Or So I Thought
- Problem: the original GNB rendering issue was fixed, but switching to mobile and tablet layouts happened during CSR, so SSR showed the desktop UI at mobile and tablet resolutions.
-
Why?
//solvook-ui-library const matchMobile = useMediaQuery(theme.breakpoints.down('sm')); const matchDownTablet = useMediaQuery(theme.breakpoints.down('lg'));The GNB’s responsive behavior uses MUI’s useMediaQuery.
https://mui.com/material-ui/react-use-media-query/#server-side-rendering
→ My understanding is that we need to send information that lets the server determine the resolution.
→ The design system’s useMediaQuery hook needs improvement so it can be used on the server too.
- When running
const theme = useTheme() const matchDownTablet = useMediaQuery(theme.breakpoints.down('lg')) console.log('matchDownTablet', matchDownTablet, theme.breakpoints.down('lg'))Client
Related discussions
https://www.reddit.com/r/nextjs/comments/n98d8s/usemediaqueryhook_that_actually_works_with_ssr/
https://medium.com/@dwinTech/managing-usemediaquery-hydration-errors-in-next-js-9ecc555542c7
-
- Change the GNB to render after mounting.
const mounted = useMounted()
return (
<WebViewWrapper>
{mounted && isUseFooter && renderGNB}
-
Problem: rerendering caused a slight flicker.
- Confirmed that _app.tsx rendered twice.
- Removed an unused useState → fixed the rerender. The flicker remained.
- The layout component called useAuth() → removed it because the information was already supplied through server-side props → flicker resolved.
-
Fix the height to minimize reflow.
const renderGNB = useMemo(() => { if (!mounted) return <SkeletonGNB/> if (goodNotesPage) return <GoodnotesGNB /> if (expertPage) return <ExpertGNB /> return <MarketGNB /> }, [mounted, pathname])
CSR version
- Conclusion)
- Create a
<SkeletonGNB/>to display during the initial server render and minimize reflow.
- Create a
- How should we change useMediaQuery?
- Replace the MUI hook with CSS.
- Or adapt useMediaQuery to work on the server, as the linked article suggests.
- Or use a media query library that supports server-side rendering.
Issue 2. The SEO Component
- Confirmed SSR was working through the Expert component.
Fixed..!
Or So I Thought
-
Problem: the meta tags were still missing.
-
Confirmed the meta tags appeared when using next-seo directly instead of the shared SEO component.
-
Found that the SEO component transformed metadata received as props through useState and useEffect. On the server, nextSeoOptions was an empty object.
const SEO = (props: SEOProps) => {
console.log('SEO props',props)
const [nextSeoOptions, setNextSeoOptions] = useState<NextSeoProps>({})
useEffect(() => {
// ... omitted
setNextSeoOptions(transformedProps)
}, [props])
console.log('nextSeoOptions', nextSeoOptions)
- Changed from transforming props inside useEffect to assigning variables directly. Since server-side rendering generates HTML for every request, separate memoization or optimization is unnecessary here. Since changes to props already trigger a rerender, I concluded there was no need to force the use of useState.
const SEO = (props: SEOProps) => {
const openGraph = _.pickBy(
{
url: props.ogUrl,
title: props.ogTitle,
description: props.ogDescription,
images: _.identity(props.ogImage) ? [{ url: props.ogImage }] : undefined,
},
_.identity,
)
const transformedProps = _.pickBy(
{
title: props.title,
description: props.description,
additionalMetaTags: _.identity(props.keywords)
? [
{
name: 'keywords',
content: props.keywords,
},
]
: undefined,
openGraph: _.isEmpty(openGraph) ? undefined : openGraph,
},
_.identity,
)
return <NextSeo {...transformedProps} />
Actually Fixed!
Remaining Improvements
- Improve the design system’s useMediaQuery to work with SSR.
- Could moving the API for the search input placeholder to server-side props improve the initial rendering experience further?
References
- Why use getInitialProps? - Differences between getInitialProps and getServerSideProps, and when to use them
- Issues using next-cookies in Next.js - Handling cookies in Next.js
- useMediaQuery hook that actually works with SSR - Discussion of useMediaQuery and SSR compatibility in Next.js
- How to implement server-side rendering for Material-UI’s media queries in Next.js - Using MUI useMediaQuery with SSR
- Managing useMediaQuery Hydration Errors in Next.js - Resolving useMediaQuery hydration errors in Next.js