How to access process.env variables inside /server/api directory in Nuxt 3?

208 Views Asked by At

In a Nuxt 3 app, I have created an /api/ folder inside the server folder of Nuxt 3, where I've created a file posts.ts. In this file, I'm integrating Ghost CMS content API. Since then, I've installed the package and imported into the post.ts file, and I'm trying to access the ENV variables through useRuntimeConfig() composable.

While doing so I'm getting the below error. How to fix it?

[nuxt] A composable that requires access to the Nuxt instance was called outside of a plugin, Nuxt hook, Nuxt middleware, or Vue setup function. This is probably ?> not a Nuxt bug. Find out more at https://nuxt.com/docs/guide/concepts/auto-imports#vue-and-nuxt-composables. at Module.useRuntimeConfig (D:\my-project\website\node_modules\nuxt\dist\app\nuxt.js:193:27) at D:\my-project\website\server\api\posts.ts:5:54

See code below:

import GhostContentAPI from '@tryghost/content-api';

const { ghostUrl, ghostKey} = useRuntimeConfig();
export const api = new GhostContentAPI({
  url: ghostUrl,
  key: ghostKey,
  version: 'v5.0'
});

I've already tried another approach of using process.env.GHOST_URL but that is also coming undefined.

import GhostContentAPI from '@tryghost/content-api';

export const api = new GhostContentAPI({
  url: process.env.GHOST_URL ?? '',
  key: process.env.GHOST_API_KEY ?? '',
  version: 'v5.0'
});
1

There are 1 best solutions below

0
On

Hello I found out that the best way to go about this is to use vite.

In your .env file define your variable as VITE_GHOST_URL="your URL"

and in the post.ts file in your server folder get the variable by const ghostUrl = ${import.meta.env.VITE_GHOST_URL}; and use the ghostUrl wherever you need the URL in the post.ts file.

This is the best approach but it will only work if your project was set up with vite.