For some reasons I can not access the .env.local file in my Next.js application. The documentation from Next js shows a function like this to pass the .env variables:
export async function getServerSideProps() {
const key = process.env.PUBLIC_API_KEY;
const secret = process.env.SECRET_API_KEY;
console.log(`Connecting with API PUBLIC: ${key} and API SECRET ${secret}`);
return {
props: {
hello: 'world',
},
};
}
However, the function I need to have acces to the API keys looks like this:
It is located in the root folder (I dont use a src folder)
Thats correct, rght? Always use .env in the root folder.
Edit: Maybe it helps, when I rename the .env file to .env.local then I lose the icon which shows up usually for .env files inside VSCode. However when I start the application the I see in the console that the .env.local file gets loaded.
If it is a route handler/controller how are you exporting it? I believe it has to be a default export. Did you try just adding export default before function.
Yes I tried to add export default before the function, but then I get this error:
Error:
x the name `default` is exported multiple times
This is the content of the whole function:
function process(req, res, detectedIp) {
// req.body contains the JSON data sent by TradingView with sub account, asset, strategy name, action (buy true or false)
const newTrigger = req.body;
triggersRepo.create(newTrigger, detectedIp);
// Get strategy item
const strategy = strategiesRepo.getByCode(newTrigger.strategy);
if (!strategy) throw 'Strategy Not Found';
// Get API key from .env
const key = process.env.PUBLIC_API_KEY;
const secret = process.env.SECRET_API_KEY;
const client = new RestClient(key, secret, {
subAccountName: newTrigger.subaccount,
});
// Get balance from FTX on specific subacount
(async () => {
processBalance(newTrigger, strategy, client, await client.getBalances());
})();
// TODO : Add LEVERAGE and FUTURES
return res.status(200).json({ status: 'ok:' });
}
EDIT: I dont see that the function gets exported, is it neccessary to export the function to have access to the .env variables?
EDIT2: I tried to export everything, but still got the same error.
Ok, I read the documentation and I tried different export method, but non of them worked. Then I added:
env: {
PUBLIC_API_KEY: 'PUBLIC_API_KEY',
},
to the next.config.js file next.js.config.js Environmental variables then I paste the PUBLIC_API_KEY to const key = { PUBLIC_API_KEY }; and of course I get the error ReferenceError: PUBLIC_API_KEY is not defined
None of this worked, but I think it has something to do with the next.config.js file because I never write something there for the .env variables.
However my head is out of order now, if someone has an idea please let me know.