Unverified Commit 5ed036d4 authored by SamPhillemon's avatar SamPhillemon Committed by GitHub

updated the example of api-routes to utilize the App Router (#68771)

This PR updates the api-routes example to use the App Router. Here are
the changes that have been made:

- Renamed the "pages" folder to the "app" folder.
- Updated the routing for /, & /person/[id] files to align with the App
Router.
- Added the layout.tsx file as part of the App Router.
- Updated the package.json file.

CC: @samcx

---------
Co-authored-by: 's avatarsamcx <sam@vercel.com>
parent 550c947a
import { NextApiRequest, NextApiResponse } from "next";
import { people } from "../../../data";
import type { Person, ResponseError } from "../../../interfaces";
export default function personHandler(
req: NextApiRequest,
res: NextApiResponse<Person | ResponseError>,
) {
const { query } = req;
const { id } = query;
const person = people.find((p) => p.id === id);
// User with id exists
return person
? res.status(200).json(person)
: res.status(404).json({ message: `User with id: ${id} not found.` });
}
# Basic API routes example
Next.js ships with [API routes](https://nextjs.org/docs/api-routes/introduction) which provides an easy solution to build your own `API`. This example shows how to create multiple `API` endpoints with serverless functions, which can execute independently.
Next.js ships with [Route Handlers](https://nextjs.org/docs/app/building-your-application/routing/route-handlers) which provides an easy solution to build your own `API`. This example shows how to create multiple `API` endpoints with serverless functions, which can execute independently.
## Deploy your own
......
import { NextResponse } from "next/server";
import { people } from "../../../../data";
import type { Person, ResponseError } from "../../../../interfaces";
export async function GET(
request: Request,
{ params }: { params: { id: string } },
): Promise<NextResponse<Person | ResponseError>> {
const { id } = params;
const person = people.find((p) => p.id === id);
if (person) {
return NextResponse.json(person);
} else {
return NextResponse.json(
{ message: `User with id: ${id} not found.` },
{ status: 404 },
);
}
}
import { NextApiResponse, NextApiRequest } from "next";
import { NextResponse } from "next/server";
import { people } from "../../../data";
import { Person } from "../../../interfaces";
export default function handler(
_req: NextApiRequest,
res: NextApiResponse<Person[]>,
) {
return res.status(200).json(people);
export async function GET(): Promise<NextResponse<Person[]>> {
return NextResponse.json(people);
}
import type { Metadata } from "next";
export const metadata: Metadata = {
title: "Home",
description: "Welcome to Next.js",
};
export default function RootLayout({
children,
}: {
children: React.ReactNode;
}) {
return (
<html lang="en">
<body>{children}</body>
</html>
);
}
"use client";
import useSWR from "swr";
import PersonComponent from "../components/Person";
import type { Person } from "../interfaces";
......@@ -6,7 +7,6 @@ const fetcher = (url: string) => fetch(url).then((res) => res.json());
export default function Index() {
const { data, error, isLoading } = useSWR<Person[]>("/api/people", fetcher);
if (error) return <div>Failed to load</div>;
if (isLoading) return <div>Loading...</div>;
if (!data) return null;
......
import { useRouter } from "next/router";
"use client";
import { useParams } from "next/navigation";
import useSWR from "swr";
import type { Person, ResponseError } from "../../interfaces";
import type { Person, ResponseError } from "../../../interfaces";
const fetcher = async (url: string) => {
const res = await fetch(url);
......@@ -13,11 +15,11 @@ const fetcher = async (url: string) => {
};
export default function PersonPage() {
const { query } = useRouter();
const query = useParams();
const { data, error, isLoading, isValidating } = useSWR<
Person,
ResponseError
>(() => (query.id ? `/api/people/${query.id}` : null), fetcher);
>(() => (query?.id ? `/api/people/${query.id}` : null), fetcher);
if (error) return <div>{error.message}</div>;
if (isLoading) return <div>Loading...</div>;
......
......@@ -2,4 +2,4 @@
/// <reference types="next/image-types/global" />
// NOTE: This file should not be edited
// see https://nextjs.org/docs/pages/building-your-application/configuring/typescript for more information.
// see https://nextjs.org/docs/app/building-your-application/configuring/typescript for more information.
{
"private": true,
"scripts": {
"dev": "next",
"dev": "next dev",
"build": "next build",
"start": "next start"
},
"dependencies": {
"next": "latest",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"swr": "^2.0.0"
"react": "^18.3.1",
"react-dom": "^18.3.1",
"swr": "^2.2.5"
},
"devDependencies": {
"@types/node": "^18.0.0",
"@types/react": "^18.0.14",
"@types/react-dom": "^18.0.5",
"typescript": "^4.7.4"
"@types/node": "^22.2.0",
"@types/react": "^18.3.3",
"@types/react-dom": "^18.3.0",
"typescript": "^5.5.4"
}
}
......@@ -13,8 +13,13 @@
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve",
"incremental": true
"incremental": true,
"plugins": [
{
"name": "next"
}
]
},
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx"],
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],
"exclude": ["node_modules"]
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment