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
[bug] using WAGMI with SSR (Next JS) is causing styling issues #542
Comments
Hey! Sorry, I completely missed the discussion thread, thanks for opening an issue here (definitely easier to keep track). Yeah, there are a couple of nuances of server/client hydration in wagmi. The main culprit of these hydration issues is that wagmi now caches responses and persists them to local storage (which is obviously not accessible on the server). This is not just a wagmi issue, but also for any library that persists state to local/session storage. Currently, there is no first-class solution for SSR in wagmi (but this is something that is on the roadmap – perhaps using cookies). There are a couple of workarounds to resolve these hydration issues right now that have their trade-offs:
function Page() {
const isMounted = useIsMounted()
if (!isMounted) return null
return (
...
)
}
function Example() {
const isMounted = useIsMounted();
const { data } = useAccount();
return (
...
{ isMounted && <div>{data?.address}</div> }
...
)
} 3 (NOT RECOMMENDED). You can turn off local storage persistance completely, which will resolve everything, but comes with the trade-off that you lose data persistence on page load (and will consequently see FOUW – flash of unconnected wallet, balances, contract data, etc) const client = createClient({
...
persister: null
})
This is probably a bug on the wagmi side - I'll take a look! |
It seems like with the current version, the |
Setting |
next example in wagmi also has the same issue.
-- {isConnected && (
++ {isMounted && isConnected && (
<button onClick={() => disconnect()}>
Disconnect from {connector?.name}
</button>
)} |
@farreldarian i saw this was merged nice #714, i imagine this fix isn't available until the next release correct? |
Correct! Will go out in the next release. |
This is not fixed, the issue should be kept open |
I'm also getting this bug and I'm using |
Hey @tmm 👋 Any chance we can get this re-opened? This issue isn't fixed quite yet. |
I was also not able to fix the hydration error with What is currently working for me is useEffect, like so: const { address, connector, isConnected } = useAccount()
const [connected, setConnected] = useState(false)
useEffect(() => {
setConnected(isConnected);
}, [isConnected]); then
Shout out to @ottodevs for this workaround. Hope that helps someone! |
This issue still persist, it's the only thing stopping me from using this wonderful lib, I really hate keep dragging isMounted hook thru my codebase, it would be awesome if you guys can prioritize this higher. |
@imornar first-class SSR support is on the roadmap, but we are holding until we see the Next.js Layouts RFC progress a little more (lots of folks use wagmi and Next.js together and we want to make sure wagmi's SSR API design is compatible with the future of Next). In the meantime, you're welcome to take some of the ideas from #689 — pass server-compatible storage to client and hydrate client state using |
@tmm Shouldn't there be like a big notice or warning that currently wagmi does not work with next.js, the most popular react framework? I finally got here after reading a bunch of issues and discussions of work arounds that had previously worked but do not as of the latest wagmi release. The example in ./examples/next shows the error: |
A temporary solution while SSR is not resolved, if you're ok with some "middleware" is to create a standalone context in your next-app where you interpret the data from wagmi. It sits between wagmi and the app itself. Basically, you create a provider and a context state more or less similar to Advantages:
|
@apecollector wagmi does work with Next.js. A first-class API would be nice, but like I said in #542 (comment), we are waiting a bit to see how the Layouts RFC progresses. In general, if you see hydration/text mismatches, you need to handle them at the app-level and follow good SSR practices. |
Not in the included example or according to others is this issue who has tried various solutions without being able to get wagmi working with next.js. If it works, why not update the example so it doesn't result in an error. |
@apecollector – we can update the examples. Update: Done. (#1040) |
issue still persists in |
For the isMounted fix, I found that neither the useIsMounted hook from usehooks-ts nor the useMountedState from react-use worked as both use a ref internally that is only set to To get it to work I had to write a simple import { useState, useEffect } from 'react'
export function useIsMounted(): boolean {
let [isMounted, setIsMounted] = useState(false)
useEffect(() => {
setIsMounted(true)
}, [])
return isMounted
} |
Filling the codebase with the For anyone who is facing the "Hydration failed" problem, maybe you could give it a try.
I found that the |
Also having this problem, I read that you wanted to explore this when next13 arrived, and since it is now in beta, I was wondering if you have an ETA on this feature? Kinda sucks to have to use workarounds in my apps, especially now since web3modal changed to the wagmi hooks in v2 (the previous hooks didn't face this problem) and a lot of extra users will be facing these problems now. Thanks in advance! @jxom |
how is this still not fixed? we are in wagmi@0.10.10 now. Please do fix this soon. Tx. |
This is not a wagmi issue that needs fixing. You should follow SSR best practices for your site. Once the Next.js app directory is out of beta, we will look into adding a first-class integration in wagmi to make this easier. |
An easy way to save developers from having to do
In the meantime, developers will probably have to put wrapper hooks around (FWIW, autoconnect has always happened to be slow enough for me that I've not run into this issue) |
You could set |
@tmm that's what everyone is currently doing, but there's an option called |
Again, once the Next.js app directory is out of beta, we can add more streamlined support. Until then, we are focused on other efforts. |
@llllvvuu – unfortunately, |
Keep in mind, this problem is not wagmi specific – it exists for anything persisted using Web Storage with Next.js. There will eventually be a first-class solution to deal with SSR & rehydration in wagmi – so please be patient. |
@tmm So do you agree that for now we cannot use Wagmi with Next 13 + App folder ? Do you recommend to use the I face a whole big issue because of that, see: #939 |
It's your call. The app directory is beta software, but should work fine if you follow hydration best-practices. |
My whole app is using next.js 13 with the app folder that next.js released. I can't use anymore the ready state here:
as it causes me the error that the whole app loading depends on this state which is client side and so nothing loads until that moment where the state is "ready" and so it gives me this error: #46968 My SEO using the Metadata API of next doesn't work because everything is basically a server side component, and the state cannot be compute in server component. Here is what i get if i remove the Is it also related to hydration ? |
I think it's okay to modify it like this.
|
Following the updated example nextjs app https://github.com/wagmi-dev/wagmi/blob/main/examples/_dev/src/pages/index.tsx, this would cause a brief flash of a blank page when navigating between routes. Does anyone have a workaround/fix for this that doesn't cause the flash? |
You need to make the workaround more precise. For example, instead of hiding the entire app on initial render, just wrap the return values of hooks. |
FWIW I suspect that the inconsistent values on initial render is related to the usage of a global |
Could you give an example of wrapping return value of a hook? For example if I'm using:
|
const _address = useAccount().address
const address = isMounted ? _address : undefined
const { data } = useContractRead({
address: isMounted ? CONTRACT_ADDRESS : undefined,
abi: CONTRACT_ABI,
functionName: "getBalance",
args: [address],
enabled: isAuthenticated && Boolean(address),
}); |
this is nasty and i love it |
next.js app router is stable (out of beta) since v13.4, which was released on may 4th, 2023: |
While the overall issue is "rendering a component that uses web storage to change its appearance fails hydration errors" which is not There's already a A solution to this scenario could be a new parameter to specify always render with Most Providing additional documentation on caching I pulled out into a separate request: #3017 |
FWIW upgrading |
I am aslo having this issue. But I am getting this error "Entire page /affiliates deopted into client-side rendering". I have a provider wrapper around my App which looks like this. "use client";
import { WagmiConfig } from "wagmi";
import { config, projectId, chains } from "utils/wagmiConfig";
import { createWeb3Modal } from "@web3modal/wagmi/react";
import { AppProgressBar } from "next-nprogress-bar";
createWeb3Modal({
wagmiConfig: config,
projectId,
chains,
});
export default function Web3ModalProvider({ children }) {
return (
<WagmiConfig config={config}>
{children}
<AppProgressBar
height="3px"
color="#7e20fc"
options={{ showSpinner: false }}
shallowRouting
/>
</WagmiConfig>
);
} which then wraps my whole app in <body>
<Web3ModalProvider>
<Layout>{children}</Layout>
</Web3ModalProvider>
</body> If I am commenting |
This issue has been locked since it has been closed for more than 14 days. If you found a concrete bug or regression related to it, please open a new bug report with a reproduction against the latest wagmi version. If you have any other comments you can create a new discussion. |
Is there an existing issue for this?
Package Version
0.3.5
Current Behavior
(copying from a discussion we previously created)
After bumping
wagmi
to0.3.5
in our project, we started to face a number of styling issues (here's an example 😆) due to a mismatch between the server-rendered HTML and the first render on the client side.After some investigation, I discovered that this was due to hooks like
useAccount
returningisLoading
astrue
during SSR, but asfalse
on the client. Here's an example of the return value ofuseAccount
during SSR and on the client:Before we upgraded to
0.3
, the SSR and client output was consistent on first render. In this case it returned:A few questions:
true
whenautoConnect
is set tofalse
?wagmi
? Currently we're manually patching this issue in many places, but I would prefer to help with a fix inwagmi
😄I would guess that anyone using Next.js + WAGMI + Stitches will face a similar issue to us.
Expected Behavior
No response
Steps To Reproduce
Styling bug isn't visible in the repo to reproduce, but mis-match between client/server output is highlighted in a console error.
Link to Minimal Reproducible Example (CodeSandbox, StackBlitz, etc.)
https://github.com/smhutch/wagmi-sandbox/blob/main/README.md
Anything else?
No response
The text was updated successfully, but these errors were encountered: