34
loading...
This website collects cookies to deliver better user experience
Create an API handler which will call the external API with the sensitive API key, then call that handler from the client-side.
const API_URL= 'https://www.test.com/api'
const API_KEY = 'some-secret-key'
useEffect(() => {
fetch(`${API_URL}/hello?apiKey=${API_KEY}`)
// ...
}, [])
const API_URL = proccess.env.NEXT_PUBLIC_EXTERNAL_API_HOST
const API_KEY = proccess.env.NEXT_PUBLIC_API_KEY;
useEffect(() => {
fetch(`${API_URL}/hello?apiKey=${API_KEY}`)
// ...
}, [])
If you're wondering why variables start with NEXT_PUBLIC_
you can refer to this blog
Keep in mind that client-side code needs to be treated as publicly accessible by anyone.
TL;DR
section, we can prevent the exposure of API keys if the code is running on the server.Check this documentation to learn about creating an API in Next.js.
NEXT_PUBLIC
in the variable name(e.g. NEXT_PUBLIC_API_KEY
to API_KEY
)hello.js
under pages/api
.export default async function handler(req, res) {
const data = await fetch(
`https://www.test.com/api/hello?apiKey=${process.env.API_KEY}`,
).then(response => response.json());
res.json(data); // Send the response
}
localhost:3000/api/hello
in a local environment or https://www.ourhost.com/api/hello
in production. OR simply via /api/hello
.useEffect(() => {
fetch(`/api/hello`)
// ...
}, [])