I am getting this error when I run netlify dev
locally and try to hit my local netlify function
SyntaxError: Unexpected end of JSON input
or sometimes
SyntaxError: Unexpected token < in JSON at position 0
I’m just starting a project and playing around with netlify functions, so I would have expected this to work without too much trouble. I am using a react project (based off of this boilerplate, but it should be the same as create-react-app for netlify dev) and the out of the box hello-world function example:
hello-world.js
const handler = async (event) => {
try {
const subject = event.queryStringParameters.name || 'World'
return {
statusCode: 200,
body: JSON.stringify({ message: `Hello ${subject}` }),
}
} catch (error) {
return { statusCode: 500, body: error.toString() }
}
}
module.exports = { handler }
netlify.toml:
[build]
functions = "serverless-functions/"
[[redirects]]
from = "api/*"
to = ".netlify/serverless-functions/:splat"
status = 200
How I call the function from my homepage:
const [helloMessage, setHelloMessage] = React.useState('')
const loadServerlessFunction = async () => {
try {
const res = await fetch('/api/hello-world')
const { message } = await res.json()
setHelloMessage(message)
} catch (error) {
console.error(error)
}
}
React.useEffect(() => {
loadServerlessFunction()
}, [])
netlify dev output:
What I see in the browser:
If I go to http://localhost:8888/, then I get this error in the console
SyntaxError: Unexpected end of JSON input
Also, after refreshing sometimes I see this error instead
SyntaxError: Unexpected token < in JSON at position 0
What I see when I invoke the function from the terminal
If I run netlify functions:invoke hello-world
then I actually do see the expected output
❯ netlify functions:invoke hello-world
◈ "port" flag was not specified. Attempting to connect to localhost:8888 by default
? Invoke with emulated Netlify Identity authentication headers? (pass --identit
y/--no-identity to override) No
{"message":"Hello World"}
and in the terminal running the server:
◈ Rewrote URL to /.netlify/serverless-functions/hello-world
Request from ::ffff:127.0.0.1: POST /.netlify/functions/hello-world
Response with status 200 in 20 ms.
I do not see the above message in the server when I try to use the function in the browser.
These feels to me like the netlify dev
proxy isn’t working, but I haven’t done anything crazy here so I’m not sure why that would be. Any insight on this would be very appreciated.