What is the best practice for accessing a private apiKey in a nextjs component?
I have a component that needs to take an apiKey as a prop:
<Component
apiKey={apiKey}
/>
Currently I am keeping that apiKey in an env.local file without the NEXT_PUBLIC_* prefix.
In env.local
API_KEY="abcdefghijk"
I'm trying to figure out the best way to get the apiKey in my component without exposing it to the client. The only way I've managed to get it working is by creating an api route which will grab the apiKey on the server side and return it as a response.
In route.ts
export async function GET(request: Request) {
return Response.json({ apiKey: process.env.API_KEY })
}
Back in my Component
const [apiKey, setApiKey] = useState("")
useEffect(() => {
fetch("/api/MyRoute").then(async (response) => {
const data = await response.json();
setApiKey(data["apiKey"])
});
}, []);
This doesn't feel like the right way to do this to me at all, any suggestions on a better practice?