Type-checking when using API Routes in Pages Router
Unanswered
Lesser Frigatebird posted this in #help-forum
Lesser FrigatebirdOP
I'm using Next.js with Typescript and when I use return of the response methods (ex.
However, if I remove the
Operating System:
Platform: linux
Arch: x64
Version: #1 SMP Thu Oct 5 21:02:42 UTC 2023
Binaries:
Node: 18.18.2
npm: 9.8.1
Yarn: 1.22.19
pnpm: N/A
Relevant Packages:
next: 14.0.2
eslint-config-next: 14.0.2
react: 18.2.0
react-dom: 18.2.0
typescript: 5.2.2
Next.js Config:
output: N/A
Code (without return statements):
res.status) I get an error: API handler should not return a value, received object.However, if I remove the
return statements and just call res.status directly Typescript starts complaining about undefined values. Looking in the docs, it doesn't show an example using a return statement so obviously this is the intended way, what am I missing?npx next info:Operating System:
Platform: linux
Arch: x64
Version: #1 SMP Thu Oct 5 21:02:42 UTC 2023
Binaries:
Node: 18.18.2
npm: 9.8.1
Yarn: 1.22.19
pnpm: N/A
Relevant Packages:
next: 14.0.2
eslint-config-next: 14.0.2
react: 18.2.0
react-dom: 18.2.0
typescript: 5.2.2
Next.js Config:
output: N/A
Code (without return statements):
import { Webhook } from 'svix'
import type { UserWebhookEvent } from '@clerk/nextjs/server'
import type { NextApiRequest, NextApiResponse } from 'next'
import { env } from "~/env.mjs";
import { db } from '~/server/db';
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
if (req.method !== 'POST') {
return res.status(405)
}
const svix_id = req.headers["svix-id"] as string;
const svix_timestamp = req.headers["svix-timestamp"] as string;
const svix_signature = req.headers["svix-signature"] as string;
if (!svix_id || !svix_timestamp || !svix_signature) {
res.status(400).json({ error: 'Invalid webhook headers' })
}
const body = req.body as UserWebhookEvent;
const webhook = new Webhook(env.CLERK_WEBHOOK_SECRET);
let clerkEvent: UserWebhookEvent
try {
clerkEvent = webhook.verify(JSON.stringify(body), {
"svix-id": svix_id,
"svix-timestamp": svix_timestamp,
"svix-signature": svix_signature,
}) as UserWebhookEvent
} catch (err) {
console.error('Error verifying webhook:', err);
res.status(400).json({ error: err })
}
const { data: clerkUserData } = clerkEvent;
if (!clerkUserData.id) res.status(500)
if (!("birthday" in clerkUserData)) {
await handleUserDeletion(clerkUserData.id)
}
else {
await handleNewUser(clerkUserData.id)
}
res.status(200)
}
async function handleNewUser(userId: string) {
return await db.user.create({ data: { id: userId } })
}
async function handleUserDeletion(userId: string) {
return await db.user.delete({ where: { id: userId } })
}