Move a Pages Router page that uses getServerSideProps to the App Router
Leaf and Kettle is moving to the App Router. Its cart page, pages/cart.tsx, reads the cart cookie in getServerSideProps and lists the teas in it. The cookie holds the teas' slugs joined by commas, like mint,green:
pages/cart.tsximport type { GetServerSideProps } from "next";
import Head from "next/head";
import { getTea, type Tea } from "@/lib/teas";
type Props = { teas: Tea[] };
export const getServerSideProps: GetServerSideProps<Props> = async ({ req }) => {
const slugs = req.cookies.cart?.split(",").filter(Boolean) ?? [];
const found = await Promise.all(slugs.map((slug) => getTea(slug)));
return { props: { teas: found.filter((tea): tea is Tea => tea !== undefined) } };
};
export default function CartPage({ teas }: Props) {
return (
<>
<Head>
<title>Your cart</title>
</Head>
<main>
<h1>Your cart</h1>
{teas.length === 0 ? (
<p>Your cart is empty.</p>
) : (
<ul>
{teas.map((tea) => (
<li key={tea.slug}>{tea.name}</li>
))}
</ul>
)}
</main>
</>
);
}
Write app/cart/page.tsx to do the same in the App Router: Your cart in an <h1>, then the teas from the cookie that the shop sells, in a list in the cookie's order, or Your cart is empty. when there are none. Give the tab the title Your cart with the Metadata API.
The app has Cache Components on, as create-next-app sets it up, so reading the cookie outside <Suspense> would stop next build. Keep the page's own component free of the request: it renders the <h1> and a <Suspense> with <p>Loading your cart…</p> as its fallback, around a component that reads the cookie.
app/cart/page.tsximport { Suspense } from "react";
import { cookies } from "next/headers";
import { getTea } from "@/lib/teas";
export default function CartPage() {
return (
<main>
<h1>Your cart</h1>
</main>
);
}
lib/teas.ts (read-only)export type Tea = { slug: string; name: string };
const teas: Tea[] = [
{ slug: "green", name: "Green tea" },
{ slug: "mint", name: "Mint tea" },
{ slug: "oolong", name: "Oolong tea" },
];
/** The tea with this slug, or undefined when the shop doesn't sell it. */
export async function getTea(slug: string): Promise<Tea | undefined> {
return teas.find((tea) => tea.slug === slug);
}
- lists the teas in the cart cookie, in the cookie's order
- leaves out teas the shop doesn't sell
- says the cart is empty without a cart cookie, or with nothing the shop sells
- keeps the heading in the static shell and reads the cookie inside <Suspense>
- titles the tab with the Metadata API
The answer
Write it yourself first. Then compare it with a reference solution and the checks it passes.
Checking your sign-in…