I'm launching my nextjs application through AWS Amplify and I have an environment variable that return undefined with called in my node application.
I defined the environment variable from the Amplify console shown here:
The variable STRAPI is a 256 character string which according to the documentation I found should be ok.
Here is the code that uses the environment variables:
import qs from "qs";
/**
* Get full Strapi URL from path
* @param {string} path Path of the URL
* @returns {string} Full Strapi URL
*/
export function getStrapiURL(path = "") {
return `${
process.env.NEXT_PUBLIC_STRAPI_API_URL || "http://localhost:1337"
}${path}`;
}
/**
* Helper to make GET requests to Strapi API endpoints
* @param {string} path Path of the API route
* @param {Object} urlParamsObject URL params object, will be stringified
* @param {Object} options Options passed to fetch
* @returns Parsed API call response
*/
export async function fetchAPI(path, urlParamsObject = {}, options = {}) {
// Merge default and user options
const token = process.env.STRAPI;
console.log("Token in process.env:");
console.log(process.env.STRAPI);
console.log("Token in token var:");
console.log(token);
const mergedOptions = {
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${token}`,
},
...options,
};
// Build request URL
const queryString = qs.stringify(urlParamsObject);
const requestUrl = `${getStrapiURL(
`/api${path}${queryString ? `?${queryString}` : ""}`
)}`;
console.log("Request url:");
console.log(requestUrl);
// Trigger API call
const response = await fetch(requestUrl, mergedOptions);
// Handle response
if (!response.ok) {
console.error(response.statusText);
throw new Error(`An error occurred please try again`);
}
const data = await response.json();
return data;
}
This code was lifted from another project credit to its original author
NEXT_PUBLIC_STRAPI_API_URL comes out fine it's just the STRAPI environment variable that comes out undefined.
Side note: I'm fully aware you shouldn't log tokens and I 100% plan on regenerating the token once the issue is resolved.
Here are the logs from CloudWatch and as you can see the NEXT_PUBLIC_STRAPI_API_URL comes out fine.
I'm not sure the issue here, but I've tried the following:
- Giving the STRAPI var a new value and it still came out as undefined after redeploying.
- I delete the env var and created a new one to see if there was some bug there and that did not resolve it after redeploying.
- I verified the setup is working locally on my machine.
Not sure what next steps to take here.
CodePudding user response:
The problem is NextJS needed the environment variable to be prefixed with NEXT_PUBLIC_ to be exposed to the application. This was introduced in about NextJS 9. It's been awhile since I used NextJS.