process.env.API_TOKEN don't work
Unanswered
Little Stint posted this in #help-forum
Little StintOP
const fetchForms = async () => {
try {
const email = session?.user?.email;
const config = {
headers: {
Authorization: `${process.env.API_TOKEN}`,
},
};
const response = await axios.get(`/api/getforms?email=${email}`, config);
setForms(response.data.formSubmissions);
console.log(response.data)
} catch (error) {
console.error('Error fetching forms:', error);
}
};14 Replies
Little StintOP
When I put the token directly it works when I use process.env it no longer works
if you want to read an env var in the client you need to prefix it with
NEXT_PUBLIC_. as the name suggests, this variable can be read by anyone so make sure it is not something private otherwise it will be leakedLittle StintOP
is the api token
@Rafael Almeida
To access the api you need a token
And this code is from frontend to connect to api
And this code is from frontend to connect to api
I don't know what is this API but in general you should avoid exposing API keys in the front-end otherwise others could abuse it. it would be better to use it in a route handler and call the route handle from the front-end instead
if you are using the app dir: https://nextjs.org/docs/app/building-your-application/routing/router-handlers
if you are using the pages dir: https://nextjs.org/docs/pages/building-your-application/routing/api-routes
if you are using the pages dir: https://nextjs.org/docs/pages/building-your-application/routing/api-routes
Little StintOP
Você fala portugues ?
I have a forms.tsx page that contains a table that loads all the contact forms that a user has submitted. It searches using the session's email, and if it matches any row in the database, it displays the information.
In the API, I used token-based authentication.
In the API, I used token-based authentication.
well I don't have the context about the project so its up to you to decide if it is secure or not to expose this variable in the front-end. I still think it would be better to only read it in the server
Little StintOP
How do I not expose the variable and still make the request to the API?
you need to create a new route handler and move this request there where you can safely read the env var. then instead of calling the API directly in the front-end code you can call this route handler which won't require the API Key to work
the route handler basically acts as a proxy
Little StintOP
How can I do this?