Movatterモバイル変換


[0]ホーム

URL:


Skip to main content
⌘K
Up or down tonavigateEnter toselectEscape toclose
On this page

Build a Next.js App

Next.js is a popular framework for buildingserver-side-rendered applications. It is built on top of React and provides alot of features out of the box.

In this tutorial, we'll build asimple Next.js application and runit with Deno. The app will display a list of dinosaurs. When you click on one,it'll take you to a dinosaur page with more details.

You can see thecomplete app on GitHub.

Deploy your own

Want to skip the tutorial and deploy the finished app right now? Click thebutton below to instantly deploy your own copy of the complete SvelteKitdinosaur app to Deno Deploy. You'll get a live, working application that you cancustomize and modify as you learn!

Deploy on Deno

Create a Next.js app with DenoJump to heading

Next provides a CLI tool to quickly scaffold a new Next.js app. In your terminalrun the following command to create a new Next.js app with Deno:

deno run-A npm:create-next-app@latest

When prompted, select the default options to create a new Next.js app withTypeScript.

Next.js has some dependencies that still rely onObject.prototype.__proto__and requires CommonJS module support. To configure Deno for Next.jscompatibility, update yourdeno.json file with the following configuration:

{"unstable":["bare-node-builtins","detect-cjs","node-globals","unsafe-proto","sloppy-imports"]}

Now install the dependencies found in the package.json:

denoinstall --allow-scripts

Now you can serve your new Next.js app:

deno task dev

This will start the Next.js development server using Deno. Thedeno task devcommand runsdev task in the package.json, which starts the Next.jsdevelopment server with the necessary flags for CommonJS compatibility.

Visithttp://localhost:3000 to see the app in thebrowser.

Add a backendJump to heading

The next step is to add a backend API. We'll create a very simple API thatreturns information about dinosaurs.

We'll use Next.js'sbuilt in API route handlersto set up our dinosaur API. Next.js uses a file-system-based router, where thefolder structure directly defines the routes.

We'll define three routes, The first route at/api will return the stringWelcome to the dinosaur API, then we'll set up/api/dinosaurs to return allthe dinosaurs, and finally/api/dinosaur/[dinosaur] to return a specificdinosaur based on the name in the URL.

/api/Jump to heading

In thesrc/app folder of your new project, create anapi folder. In thatfolder, create aroute.ts file, which will handle requests to `/api/.

Copy and paste the following code into theapi/route.ts file:

route.ts
exportfunctionGET(){return Response.json("welcome to the dinosaur API");}

This code defines a simple route handler that returns a JSON response with thestringwelcome to the dinosaur API.

/api/data.jsonJump to heading

In theapi folder, create adata.json file, which will contain the hardcoded dinosaur data. Copy and pastethis json fileinto thedata.json file.

/api/dinosaursJump to heading

In theapi folder, create a folder calleddinosaurs, in that create aroute.ts file which will handle requests to/api/dinosaurs. In this routewe'll read thedata.json file and return the dinosaurs as JSON:

route.ts
import datafrom"./data.json"with{ type:"json"};exportfunctionGET(){return Response.json(data);}

/api/dinosaurs/[dinosaur]Jump to heading

And for the final route,/api/dinosaurs/[dinosaur], we'll create a foldercalled[dinosaur] in thedinosaurs directory. In there, create aroute.tsfile. In this file we'll read thedata.json file, find the dinosaur with thename in the URL, and return it as JSON:

route.ts
import datafrom"../../data.json"with{ type:"json"};typeRouteParams={ params:Promise<{ dinosaur:string}>};exportconstGET=async(_request: Request,{ params}: RouteParams)=>{const{ dinosaur}=await params;if(!dinosaur){return Response.json("No dinosaur name provided.");}const dinosaurData= data.find((item)=>    item.name.toLowerCase()=== dinosaur.toLowerCase());return Response.json(dinosaurData? dinosaurData:"No dinosaur found.");};

Now, if you run the app withdeno task dev and visithttp://localhost:3000/api/dinosaurs/brachiosaurus in your browser, you shouldsee the details of the brachiosaurus dinosaur.

Build the frontendJump to heading

Now that we have our backend API set up, let's build the frontend to display thedinosaur data.

Define the dinosaur typeJump to heading

Firstly we'll set up a new type, to define the shape of the dinosaur data. Intheapp directory, create atypes.ts file and add the following code:

types.ts
exporttypeDino={ name:string; description:string};

Update the homepageJump to heading

We'll update thepage.tsx file in theapp directory to fetch the dinosaurdata from our API and display it as a list of links.

To execute client-side code in Next.js we need to use theuse Client directiveat the top of the file. Then we'll import the modules that we'll need in thispage and export the default function that will render the page:

page.tsx
"use client";import{ useEffect, useState}from"react";import{ Dino}from"./types";import Linkfrom"next/link";exportdefaultfunctionHome(){}

Inside the body of theHome function, we'll define a state variable to storethe dinosaur data, and auseEffect hook to fetch the data from the API whenthe component mounts:

page.tsx
const[dinosaurs, setDinosaurs]=useState<Dino[]>([]);useEffect(()=>{(async()=>{const response=awaitfetch(`/api/dinosaurs`);const allDinosaurs=await response.json()as Dino[];setDinosaurs(allDinosaurs);})();},[]);

Beneath this, still inside the body of theHome function, we'll return a listof links, each linking to the dinosaur's page:

page.tsx
return(<mainid="content"><h1>Welcome to the Dinosaur app</h1><p>Click on a dinosaur below to learn more.</p><ul>{dinosaurs.map((dinosaur: Dino)=>{return(<likey={dinosaur.name}><Linkhref={`/${dinosaur.name.toLowerCase()}`}>{dinosaur.name}</Link></li>);})}</ul></main>);

Create the dinosaur pageJump to heading

Inside theapp directory, create a new folder called[dinosaur]. Inside thisfolder create apage.tsx file. This file will fetch the details of a specificdinosaur from the API and render them on the page.

Much like the homepage, we'll need client side code, and we'll import themodules we need and export a default function. We'll pass the incoming to thefunction and set up a type for this parameter:

[dinosaur]/page.tsx
"use client";import{ useEffect, useState}from"react";import{ Dino}from"../types";import Linkfrom"next/link";typeRouteParams={ params:Promise<{ dinosaur:string}>};exportdefaultfunctionDinosaur({ params}: RouteParams){}

Inside the body of theDinosaur function we'll get the selected dinosaur fromthe request, set up a state variable to store the dinosaur data, and write auseEffect hook to fetch the data from the API when the component mounts:

[dinosaur]/page.tsx
const selectedDinosaur= params.then((params)=> params.dinosaur);const[dinosaur, setDino]=useState<Dino>({ name:"", description:""});useEffect(()=>{(async()=>{const resp=awaitfetch(`/api/dinosaurs/${await selectedDinosaur}`);const dino=await resp.json()as Dino;setDino(dino);})();},[]);

Finally, still inside theDinosaur function body, we'll return a paragraphelement containing the dinosaur's name and description:

[dinosaur]/page.tsx
return(<mainid="content"><h1>{dinosaur.name}</h1><p>{dinosaur.description}</p><Linkhref="/">🠠 Back to all dinosaurs</Link></main>);

Add some stylesJump to heading

Let's add some basic styles to make the app look nicer. Update yourapp/globals.css file with thestyles from this file.

Run the appJump to heading

Now you can run the app withdeno run dev and visithttp://localhost:3000 inyour browser to see the list of dinosaurs. Click on a dinosaur to see moredetails!

Deploy the appJump to heading

Now that you have your working Next.js app, you can deploy it to the web withDeno Deploy.

For the best experience, you can deploy your app directly from GitHub, whichwill set up automated deployments. Create a GitHub repository and push your appthere.

Create a new GitHub repository, then initialize andpush your app to GitHub:

git init-b maingit remoteadd origin https://github.com/<your_github_username>/<your_repo_name>.gitgitadd.git commit-am'my next app'git push-u origin main

Once your app is on GitHub, you candeploy it to Deno Deploy.

For a walkthrough of deploying your app, check out theDeno Deploy tutorial.

🦕 Now you can build and run a Next.js app with Deno! To build on your app youcould consideradding a databaseto replace yourdata.json file, or considerwriting some tests to make your app reliableand production ready.

Did you find what you needed?

What can we do to improve this page?

If provided, you'll be @mentioned in the created GitHub issue

Privacy policy

[8]ページ先頭

©2009-2025 Movatter.jp