Next.js Discord

Discord Forum

API routing in APP dir

Answered
Caya posted this in #help-forum
Open in Discord
So here is my file structure
/app
  /api
    /user
      check.ts


and here is the check.ts code

import type { NextApiRequest, NextApiResponse } from "next";

type ResponseData = {
  message: string;
};

export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse<ResponseData>
) {
  if (req.method !== "GET") {
    return res.status(405).json({ message: "Method Not Allowed" });
  }

  const { user } = req.query;

  if (typeof user !== "string" || !user) {
    return res.status(400).json({ message: "No user provided" });
  }

  try {
    const response = await fetch(`https://api.github.com/users/${user}`);

    if (response.status === 404) {
      return res.status(404).json({ message: "User not found" });
    }

    return res.status(200).json({ message: "User found" });
  } catch (error) {
    return res.status(500).json({ message: "Internal server error" });
  }
}


its a simple api route which will check if a user exist on github or not i'm using it just to check how next js api works...

so i tried going to sending req (through postman) to the flloing urls but all of them sends me to NextJs default 404 page

1. https://localhost:3000/api/user?user=username
2. https://localhost:3000/api/user=username
3. https://localhost:3000/api/username
4. https://localhost:3000/api/user

ik 2,3,4 will not give any result still i tried
Answered by joulev
Yes, see point 2 above.
View full answer

4 Replies

@joulev 1. It is app/api/user/check/route.ts 2. https://nextjs-faq.com/route-handler-using-pages-router-syntax
i was using cehck.ts but stwitch to check/route.ts and got a 405 error
Answer
@joulev Yes, see point 2 above.
ahh thats what i'm looking for thanks