Next.js Discord

Discord Forum

Getting 404 responses on API routes even though already defined.

Answered
Cape lion posted this in #help-forum
Open in Discord
Cape lionOP
Hey, so I am using NextJS 14 with App router. I have a api route - /api/stripe/customer. I am basically creating a customer id on here and returning data with Stripe.

When I make a request from the frontend with fetch:
      const req = await fetch("/api/user/stripe", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          email: data.email,
          name: data.fullname,
        }),
      });


I seem to be getting this error on the console:
SignUpComponent.tsx:32 
        
        
       POST http://localhost:3000/api/user/stripe 404 (Not Found)


I have checked the route names, googled around but could not find anything regarding this error. Would be grateful if someone can tell me what I'm doing wrong
Answered by Cape lion
Okay, turns out I'm an idiot. I had to configure the middleware.ts file
View full answer

5 Replies

can u share your file structure and the code inside the route?
@B33fb0n3 can u share your file structure and the code inside the route?
Cape lionOP
here's the route handler code;
import { NextRequest, NextResponse } from "next/server";
import Stripe from "stripe";

const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!, {
  apiVersion: "2024-04-10",
});

export async function POST(req: NextRequest) {
  try {
    const { email, name } = await req.json();

    const customer = await stripe.customers.create({
      email: email,
      name: name,
    });

    return NextResponse.json(
      {
        message: "Created Stripe customer successfully",
        status: true,
        data: customer,
      },
      {
        status: 201,
      },
    );
  } catch (err: any) {
    console.error(err.message);

    return NextResponse.json(
      {
        message: "Could not create Stripe customer",
        data: null,
        status: false,
      },
      { status: 500 },
    );
  }
}
file structure is:
app/
  api/
    user/
      stripe/
        route.ts
I even tried change the route but it's still giving the same error
Cape lionOP
Okay, turns out I'm an idiot. I had to configure the middleware.ts file
Answer