My solution involved a combination of analyzing URLs and passing server props to the client side.
For instance, I made sure my backend sent certain styles like primaryColor
.
Here is a functional example:
- Before rendering in your page.tsx file, extract the tenantId from the URL and use it to fetch styles from the backend.
async function retrieveQueryParams() {
const headersInstance = headers();
const pathname = headersInstance.get("referer");
if (!pathname) return new URLSearchParams();
const urlSearchParams = new URLSearchParams(pathname.split("?")[1]);
return urlSearchParams;
}
async function fetchStyles(tenantId: string) {
try {
const response = await fetch(`http://localhost:3000/themes/${tenantId}`);
return response.json();
} catch (error) {
return {};
}
}
- Access this data in your server component and pass it to your client component
export default async function Main({searchParams){
const tenantId = searchParams?.tenantId || "";
const styles = await fetchStyles(tenantId);
return (
<div>
<ClientComponent styles={styles} />
</div>
)
}
- In your client component, dynamically update the global CSS variables
const ClientComponent = ({styles}) => {
useEffect(() => {
document.documentElement.style.setProperty("--primary-color", primaryColor);
}, [primaryColor]);
return (
<div className="bg-primary w-100 h-100">
my colour has been changed
</div>