So I have a project that has 4 api keys that I need hidden:
STORYBLOK_API_KEY=
EMAILJS_SERVICE_ID=
EMAILJS_USER_ID=
EMAILJS_TEMPLATE_ID=
All 4 of them I am using with process.env.XXX, the funny thing is that, the storyblok key is working (but it is not used within a component), however the other 3 I am using within a form submission function:
const sendContactForm = async (formData) => {
const data = {
service_id: process.env.EMAILJS_SERVICE_ID,
template_id: process.env.EMAILJS_TEMPLATE_ID,
user_id: process.env.EMAILJS_USER_ID,
template_params: { ...formData, form: "Discover form" },
};
try {
const response = await axios.post("https://api.emailjs.com/api/v1.0/email/send", data);
console.log(response);
} catch (e) {
console.log(e);
}
};
And they are not working here, they are undefined. I have tried:
All 3 approaches did not work.
Did you read documentation exactly? How we can add Environment Variables in Next.js? Below you have simple example from docs.
.env.local
DB_HOST=localhost
DB_USER=myuser
DB_PASS=mypassword
This loads process.env.DB_HOST, process.env.DB_USER, and process.env.DB_PASS into the Node.js environment automatically allowing you to use them in Next.js data fetching methods and API routes.
example:
// pages/index.js
export async function getStaticProps() {
const db = await myDB.connect({
host: process.env.DB_HOST,
username: process.env.DB_USER,
password: process.env.DB_PASS,
})
// ...
}
Environment variables are only available in the Node.js(serverside
) environment, meaning they won't be exposed to the browser.
In order to expose a variable to the browser(clientside) you have to prefix the variable with NEXT_PUBLIC_. For example:
NEXT_PUBLIC_ANALYTICS_ID=123456xyzabcde
Here You Have All examples of using environment-variables in Next.js . Good Luck ;-)