treefarmstudio / astro-sanity

This is a helper package to integrate Astro and Sanity
https://www.npmjs.com/package/astro-sanity
MIT License
102 stars 10 forks source link

`useSanityClient()` doesn't work within Astro SSR endpoints #26

Open ehcc-admin opened 1 year ago

ehcc-admin commented 1 year ago

Description

I've found that useSanityClient() within an SSR endpoint works to query Sanity while in dev mode but breaks in production mode. This specifically only occurs when using Server Endpoints (API Routes) files. Queries work fine when imported/run within .astro files.

The error says "Sanity client has not been initialized correctly" and the resolved client object appears to be undefined.

I tried a couple of alternative approaches:

Configuration

Astro config:

export const sanityClientConfig = {
  projectId: 'abc123',
  dataset: 'production',
  apiVersion: '2021-03-25',
  useCdn: true,
};

export default defineConfig({
  site: 'https://website.com/',
  output: 'hybrid',
  adapter: cloudflare(),
  integrations: [
    solidJs(),
    tailwind({
      config: {
        applyBaseStyles: false,
      },
    }),
    sanity(sanityClientConfig),
  ],
  vite: {
    ssr: {
      external: ['svgo'],
    },
  },
});

Endpoint code is something like this:

import type { APIRoute } from 'astro';
import type { Program } from 'schemas/program';
import { useSanityClient } from 'astro-sanity';

export const prerender = false;

export const get: APIRoute = async ({ url }) => {
  const start = url.searchParams.get('start');
  const end = url.searchParams.get('end');

  if (!start || !end) {
    return new Response(null, {
      status: 404,
      statusText: 'Not found',
    });
  }

  const programs = await useSanityClient().fetch<Program[]>(`
    *[_type == 'program' && endDate >= $start && startDate <= $end]{
      'title': name,
      'url': '/program/' + slug.current,
      'start': startDate,
      'end': endDate,
    }`, { start, end });

  return new Response(JSON.stringify(programs), {
    status: 200,
    headers: {
      'Content-Type': 'application/json',
    },
  });
};

Expected behavior

I'd like to be able to query Sanity from a SSR endpoint file.

Error messages

The error Cloudflare reports when sent live:

GET https://website.com/programs/calendar.json?start=2023-05-28T00%3A00%3A00-10%3A00&end=2023-07-09T00%3A00%3A00-10%3A00 - Exception Thrown @ 6/27/2023, 10:15:31 PM
  (error) Sanity client has not been initialized correctly
X [ERROR]   TypeError: Cannot read properties of undefined (reading 'fetch')

Here's the error I get in astro preview mode:

[mf:err] TypeError: Cannot read properties of undefined (reading 'fetch')
    at Module.zl [as get] (../projectfolder/dist/_worker.js:71:6370)
    at Bn (../projectfolder/dist/_worker.js:24:81)
    at Ja (../projectfolder/dist/_worker.js:52:1307)
    at ht.Br (../projectfolder/dist/_worker.js:62:56143)
    at async Object.fetch (../projectfolder/dist/_worker.js:77:1806)
    at async jsonError (../projectfolder/node_modules/.pnpm/wrangler@3.1.0/node_modules/wrangler/templates/middleware/middleware-miniflare3-json-error.ts:22:10)
    at async jsonError (../projectfolder/node_modules/.pnpm/wrangler@3.1.0/node_modules/wrangler/templates/middleware/middleware-miniflare3-json-error.ts:22:10)
    at async jsonError (../projectfolder/node_modules/.pnpm/wrangler@3.1.0/node_modules/wrangler/templates/middleware/middleware-miniflare3-json-error.ts:22:10)
    at async Object.fetch (../projectfolder/dist/_worker.js:77:1806)
    at async jsonError (../projectfolder/node_modules/.pnpm/wrangler@3.1.0/node_modules/wrangler/templates/middleware/middleware-miniflare3-json-error.ts:22:10)
    at async jsonError (../projectfolder/node_modules/.pnpm/wrangler@3.1.0/node_modules/wrangler/templates/middleware/middleware-miniflare3-json-error.ts:22:10)
    at async jsonError (../projectfolder/node_modules/.pnpm/wrangler@3.1.0/node_modules/wrangler/templates/middleware/middleware-miniflare3-json-error.ts:22:10)
    at async jsonError (../projectfolder/node_modules/.pnpm/wrangler@3.1.0/node_modules/wrangler/templates/middleware/middleware-miniflare3-json-error.ts:22:10)
    at async jsonError (../projectfolder/node_modules/.pnpm/wrangler@3.1.0/node_modules/wrangler/templates/middleware/middleware-miniflare3-json-error.ts:22:10)
Sanity client has not been initialized correctly
A promise rejection was handled asynchronously. This warning occurs when attaching a catch handler to a promise after it rejected. (rejection #2)