I believe I’m experiencing issues with accessing the API key that I’ve set under Netlify env variables. Application is deployed fine, but fetching to unsplash via button click results in 500 error, “Uncaught (in promise) SyntaxError: Unexpected token ‘R’, “ReferenceE”… is not valid JSON”:
https://just-the-cat-facts.netlify.app/
Not using dotenv or webpack, this is a simple HTML/JS application. My fetch with the API secret key (in an .env file) works fine locally via netlify dev, but not on deploy. I did set my API key using the same variable name and value on the Netlify UI (although I did it via CLI command), checked the value which looks exactly the same on Netlify as it does in my .env file. Please help?? I’m including my function and my netlify.toml file.
I’ve read seemingly all the posts here and elsewhere as well as the docs, some of which makes sense and some of which is over my head. Def not a dev ops expert… Thanks in advance!!!
My netlify function is in a file called fetch-unsplash.js which is located inside the top level functions directory.
const handler = async (event) => {
const API_KEY = process.env.API_KEY
console.log("looking for this value in my logs: ", API_KEY)
// this does not log anything in the build logs, sadly
const URL = `https://api.unsplash.com/photos/random?Accept-Version=v1&client_id=${API_KEY}&username=theluckyneko`
try {
const resp = await fetch(URL)
const result = await resp.json()
return {
statusCode: 200,
body: JSON.stringify({ message: result })
}
} catch (error) {
return { statusCode: 500, body: error.toString() }
}
}
module.exports = { handler }
netlify.toml file is simple:
[build]
functions = "functions/"
publish = ""
function inside my index.js is simple, just calls the fetch-unsplash endpoint and does some stuff…
const fetchCatPic = async () => {
const resp = await fetch('/.netlify/functions/fetch-unsplash')
const result = await resp.json()
kitties.src = result.message.urls.small
kitties.alt = result.message.alt_description
}