astro-sanity icon indicating copy to clipboard operation
astro-sanity copied to clipboard

Integration doesn't work in ssr

Open MoustaphaDev opened this issue 2 years ago • 4 comments

This integration doesn't work in ssr mode (output:'server' in astro config). This is because initSanityClient(options) is only called in astro:config:setup hook which only runs during dev and build AFAIK

MoustaphaDev avatar Sep 21 '22 00:09 MoustaphaDev

Thanks for reporting this! I can confirm it is in fact a bug. I'll see what I can do to support SSR ASAP. 👍🏼

jaydanurwin avatar Oct 14 '22 02:10 jaydanurwin

I reported basically a similar issue here for the storyblok astro plugin, it appears to be any Astro plugin wrote in the same manner using globalThis will exhibit this issue https://github.com/storyblok/storyblok-astro/issues/46

Not too sure what the fix is exactly, but figured I'd drop this here

cbarratt avatar Oct 26 '22 15:10 cbarratt

Having similar issue with cloudflare pages. basically seems like in setup sanity is attached to globalthis successfully. But that is not the service worker process running later when called to render routes.

BtheGit avatar Oct 30 '22 22:10 BtheGit

@jaydanurwin You should take a look at the injectSrcipt option. I've not tested this but seem like this could do the trick

export default function astroSanityIntegration(options: ClientConfig): AstroIntegration {
	return {
		name: 'astro-sanity',
		hooks: {
			'astro:config:setup': ({injectScript, config}) => {
				if (config.output === "static"){
					return initSanityClient(options)
				}
				const code = 
				`if (!globalThis.sanity){
					const sanityClient = (await import('@sanity/client')).default;
					const client = sanityClient(${JSON.stringify(options)});
					globalThis.sanity = client;
				}`

				injectScript("page-ssr", code)
			},
		},
	};
}

I'll experiment more when I have some time and submit a PR if I get it working

MoustaphaDev avatar Oct 31 '22 10:10 MoustaphaDev

Is there any progress on this issue? Still getting it.

pijusz avatar Dec 30 '22 10:12 pijusz

I have it on my todo list today to dig into this actually. Progress is being made over on the next branch!

jaydanurwin avatar Dec 30 '22 16:12 jaydanurwin

I'm still testing but this might have been fixed with the latest version of Astro (1.7.2). It's building successfully for me in SSR mode.

@MoustaphaDev Can you confirm on your end?

jaydanurwin avatar Dec 30 '22 17:12 jaydanurwin

Scratch that, you're right. It's building and running in dev but it won't serve once it's deployed.

jaydanurwin avatar Dec 30 '22 17:12 jaydanurwin

This is fixed! 🎉

Please upgrade to v1.1.1 and you should be able to use the setup described in the docs and shown in the demos.

Special thanks to the storyblok-astro repo for leading me in the right direction on how to fix it. If you still are having issues with SSR please reach out.

jaydanurwin avatar Dec 30 '22 19:12 jaydanurwin