mattddean
mattddean
TTCTheo's Typesafe Cult
Created by mattddean on 6/27/2023 in #questions
Detect server/client component
Anyone know of a way to detect at runtime whether a component is running as a server component or as a client component? I'm building a custom Cloudflare Image component which has additional functionality when running on the server, and ideally I'd like to be able to import one component into a client or a server component and have it use the server component "version" when imported into a server component. I don't care too much about having to write <CloudflareImageClient> or <CloudflareImageServer>, except that I might have a component which is sometimes a server component and sometimes a client component depending on what imports it. Here's an example, where <Hero> may run as either a server component or a client component.
export const Hero: FC = () => {
// When Hero is imported into a server component, I'd like this to use <CloudflareImageServer>.
// When Hero is imported into a client component, I'd like this to use <CloudflareImageClient>.
return <CloudflareImage></CloudflareImage>
}
export const Hero: FC = () => {
// When Hero is imported into a server component, I'd like this to use <CloudflareImageServer>.
// When Hero is imported into a client component, I'd like this to use <CloudflareImageClient>.
return <CloudflareImage></CloudflareImage>
}
// home/page.tsx
export const Page: NextPage = () => {
<Hero></Hero>
}
// home/page.tsx
export const Page: NextPage = () => {
<Hero></Hero>
}
// components/some-client-component.tsx
'use client'

export const SomeClientComponent: FC = () => {
<Hero></Hero>
}
// components/some-client-component.tsx
'use client'

export const SomeClientComponent: FC = () => {
<Hero></Hero>
}
I don't think it's sufficient to check typeof window === undefined, since that'll be true for client components when they initially run on the server. I'm also open to hearing that this is fundamentally impossible based on how importing client and server components works in Next.js. It feels like that's probably the case.
18 replies
TTCTheo's Typesafe Cult
Created by mattddean on 3/5/2023 in #questions
App Dir + tRPC + Edge
Anyone have an example repo combining these three? Basically looking for emojer but in a public repo.
6 replies