Using clientside only library with nextjs (t3)

I have been working on a rebuild of an ancients system that we use in nextjs (t3 all in with ts) however we require to use a javascript library for connecting to our printers (dymo labelwriter sdk), what is the best way to achieve using the library with the t3stack without getting hydration issues or a load of type errors and not having the library run on the server side? (the library is old and kinda shitty and I don't feel like trying to rewrite it)
2 Replies
Matvey
Matvey3y ago
Move the code that interacts with the library into a separate component and load it only on client. You can also rename the file with this component from .tsx to .jsx, if you encounter a lot of type errors, but usually js libraries work fine inside ts, you just don't get any autocomplete and typechecking.
{typeof window !=== 'undefined' && <ClientSideComponent />}
{typeof window !=== 'undefined' && <ClientSideComponent />}
devjo-ca
devjo-ca3y ago
as Ronan told you, you can extract it to a separate component. You could leverage the dynamic import from nextjs:
import dynamic from "next/dynamic";

const ClientSideComponent = dynamic(
() => import("./client-side-component"),
{
ssr: false,
}
);
import dynamic from "next/dynamic";

const ClientSideComponent = dynamic(
() => import("./client-side-component"),
{
ssr: false,
}
);
after that you can use your component without checking if typeof window is defined

Did you find this page helpful?