I am creating https://goldens-living-pokedex.netlify.app/ in order to learn how to use databases and SQL, and have it set up to attempt to call the first 30 items from the connected database when I press the button. The production deployment (linked) runs into a 404 error, but when I run it locally I instead get “SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data” as the error.
Here is the function code, located at netlify/functions/api/boxes.ts:
import { drizzle } from 'drizzle-orm/netlify-db'
import * as schema from '../../../db/schema'
const db = drizzle(process.env.NETLIFY_DB_URL!);
export async function handler(event: { path: string }) {
const path = event.path.replace('/netlify/functions/api', '');
try {
//fetch the first box of pokedex entries
if (path === '/box1' || path === '') {
const result = await db.select().from(schema.pokedex).limit(30);
return {
statusCode: 200,
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(result)
}
}
return {
statusCode: 404,
body: JSON.stringify({ error: 'Not Found' })
}
} catch (err) {
console.error('Database error:', err)
return {
statusCode: 500,
body: JSON.stringify({ error: 'Database query failed' })
}
}
}
Here is the react code meant to call the function:
const fetchBoxOne = async() => {
try {
setLoading(true);
const res = await fetch('/netlify/functions/api/box1');
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const data = await res.json();
setBox(data);
} catch (err) {
console.error('Fetch error:', err);
setError(err instanceof Error ? err.message : 'Unknown error');
}
finally {
setLoading(false);
}
}
Getting it to log res (when running locally) and poking around shows it has nothing for .json() to parse but I don’t know how to get it to get something from the database.
I’m not sure the difference between the production and local run which causes the difference in error.
Is anyone able to help? Am I missing something important for getting it to work?