Next.js Discord

Discord Forum

How can I write this API handler for App router?

Unanswered
Airedale Terrier posted this in #help-forum
Open in Discord
Airedale TerrierOP
Hi, I'm lost.

I can see that this is not correct but I'm struggling to figure out how this is should be written:

import { MongoClient } from "mongodb"; import { NextResponse, NextRequest } from "next/server"; export async function handler(req, res) { console.log("handler started", req.body) if (req.method === "POST") { try { const { email, name, title, concept } = req.body; if ( !email || !email.includes("@") || !name || name.trim() === "" || !title || title.trim() === "" || !concept || concept.trim() === "" ) { NextResponse.json({ message: "Invalid input." }); return; } const newConcept = { email, name, title, concept, }; let client; try { client = await MongoClient.connect( "mongodb+srv://<hidden>:<hidden>@cluster0.6ap8sjr.mongodb.net/adv-prog?retryWrites=true&w=majority" ); } catch (error) { NextResponse.json({ message: "Could not connect to the database." }); return; } const db = client.db(); try { const result = await db.collection("concepts").insertOne(newConcept); newConcept.id = result.insertedId; } catch (error) { client.close(); NextResponse.json({ message: "Storing concept failed." }); return; } NextResponse.json({ message: "Successfully stored concept!", concept: newConcept }); } catch (error) { NextResponse.json({ message: "Internal server error." }); } } else { NextResponse.json({ message: "Method Not Allowed" }); } }

4 Replies

you don't have a function handler( in App Router, you have a function POST(
also use triple back tick for code blocks, not individual lines of code
@Shy Albatross https://nextjs.org/docs/app/building-your-application/routing/route-handlers
Airedale TerrierOP
Thank you for your reply