cosmicjs / cosmicjs-node

*API v2 JavaScript client for Cosmic. See important message in README
https://www.cosmicjs.com
MIT License
274 stars 38 forks source link

Cannot read properties of undefined (reading 'COSMIC_API_URL') #72

Closed AlexBa closed 2 years ago

AlexBa commented 2 years ago

Hello, I'm using Nuxt 3 (SSR) with Cosmic.JS and getting the following error:

Bildschirmfoto 2022-09-06 um 14 46 21

Here is my plugin I created unter plugins/cosmic.ts:

import Cosmic from 'cosmicjs'

const api = Cosmic();
const bucket = api.bucket({
  slug: process.env.COSMIC_JS_BUCKET_SLUG,
  read_key: process.env.COSMIC_JS_READ_KEY,
});

export default defineNuxtPlugin(() => ({
  provide: {
    cosmic: bucket
  }
}));

Maybe it's necessary to check if "process.env" is existing?

tonyspiro commented 2 years ago

Hey @AlexBa I'm not super familiar with Nuxt 3. Tagging @jazibsawar to see if he can offer advice. Thanks 🙌🏻

jazibsawar commented 2 years ago

Hey @AlexBa I'm not really sure how NUXT is handling SSR. But apparently, process.env is undefined in SSR mode which shouldn't be in the Node environment.

AlexBa commented 2 years ago

@jazibsawar I tested a few things and found out that Nuxt 3 uses the same code for the frontend and backend (hydration and SSR). And process.env is not available with Vite in the frontend.

I guess that it's not possible to add your NPM library the "Nuxt 3 way" via plugins, BUT it's possible to create an API endpoint unter server/api, which is served always via Node in the backend. It's possible to call the backend in the frontend via "fetch".

Now it's working! :)

tonyspiro commented 2 years ago

Great to hear @AlexBa I'll go ahead and close this issue.