I'm having issue with ENV variables. On the first request with :
export const getStaticProps = async () => {
const posts = await getPosts(1);
return { props: posts, revalidate: 5 };
};
everything goes fine and it fetchs all the data, but on button click i want to fetch new data and i got 404 :
xhr.js:177 GET http://localhost:3000/fr/undefined/ghost/api/v3/content/posts?key=undefined&fields=id%2Ctitle%2Cfeature_image%2Cslug%2Cexcerpt%2Ccustom_excerpt%2Creading_time%2Ccreated_at&include=authors%2Ctags&page=2 404 (Not Found)
as you can see env variables result to undefined , i dont know why. how i fetch the data :
const fetchNewData =async (currentPage)=>{
console.log(currentPage);
const post = await getPosts(currentPage)
console.log(post);
}
How i use env
export const CONTENTKEY=process.env.contentKey
export const BLOG_API = process.env.blogApiLink;
import axios from "axios";
import {BLOG_API,CONTENTKEY} from "../segret_keys"
export const getPosts = async (page) => {
const pageUrl =
BLOG_API +
"/ghost/api/v3/content/posts/?key=" +
CONTENTKEY +
"&fields=id,title,feature_image,slug,excerpt,custom_excerpt,reading_time,created_at&include=authors,tags&page=" +
page;
console.log(pageUrl);
return axios({
method: "get",
url: pageUrl,
}) //&filter=tag:blog,tag:Blog
.then((res) => {
return { status: res.status, data: res.data };
})
.catch((err) => {
console.log(err.response.status, err.response.data);
return { status: err.response.status, data: "" };
});
};
According to docs you can use NEXT_PUBLIC_ prefix to expose Environment Variables to the Browser:
env.local
NEXT_PUBLIC_contentKey=somevalue
Use:
process.env.NEXT_PUBLIC_contentKey
Other approach:
next.config.js
module.exports = {
publicRuntimeConfig: {
contentKey: process.env.contentKey,
blogApiLink: process.env.blogApiLink,
}
}
Access to env variables value:
import getConfig from "next/config";
const { publicRuntimeConfig } = getConfig();
export const CONTENTKEY= publicRuntimeConfig.contentKey
export const BLOG_API = publicRuntimeConfig.blogApiLink;