I am using nextjs 13 and the postgresql provided by vercel, I have created a few routes, here’s an example of one of them:
get-testcase.ts
import { NextApiRequest, NextApiResponse } from 'next';
import { sql } from '@vercel/postgres';
export default async function handler(
request: NextApiRequest,
response: NextApiResponse
) {
try {
const { id } = request.query;
const idString = Array.isArray(id) ? id[0]?.toString() : id?.toString();
if (!idString) throw new Error('ID is required');
const { rows } = await sql`SELECT * FROM Testcases WHERE ID = ${idString}`;
if (rows.length === 0) {
return response.status(404).json({ error: 'Test case not found' });
}
const testCase = rows[0];
return response.status(200).json({ testCase });
} catch (error) {
return response.status(500).json({ error: 'Error fetching test case' });
}
}
this file is located in app/api/get-testcase.ts
everything seems to be correct, but everytime I try using the route I get 404 not found.
here’s what happens when I navigate to this route:
‘http://localhost:3000/api/get-testcases’
image attached below, again 404 not found
A similar thing is happening with the other postgresql routes, but I have some other routes which function properly.
Keep in mind that I am new to nextjs so if the problem is something trivial, I apologise.
I tried confirming the project directory, navigating to the route directly on the browser and using postman canary, consulted the docs and even gpt and I can’t seem to find what was wrong.
2
Answers
Refer to Next.js App router documentation:
In the code sample you provided, new "app router" conventions are mixed with old "pages router" conventions.
If you want to use new "app router", you should save your handler as
app/api/get-testcase/route.ts
AND change your export signature like this:where
Request
is just native Node.js Request class. No need to importNextApiRequest
then.You can also use old "pages router". In order to do that, just save your handler as
src/api/get-testscase.ts
and keep the export signature like you have:With Next 13 and an app dir you’ll need to setup your directory differently.
It has to be:
app/api/get-testcase/route.ts
.Also, you’ll have to export your handler for the HTTP methods you need, i.e.:
Or setup each individually, e.g.: