Next.js 13のコード変更点(パス取得/リダイレクト/リクエストbodyの解析など)
2023.05.18
目次
この記事の筆者:三好アキ(エンジニア)
ウェブデザイナーから『エンジニア』『プログラマー』へ成長したい人、独学で進んでいきたい人を応援しています。 HTMLとCSSの知識だけでアプリ開発を始められる入門書を多数執筆中📕📗👇
ウェブ制作の教本『はじめてつくるReactアプリ』など複数冊を執筆。
React、Next.js、TypeScriptなどのお役立ち情報や実践的コンテンツを、ビギナー向けにかみ砕いて配信中。登録はこちらから → 無料メルマガ登録
Next.js v13の変更点
Next.js 13ではReactサーバーコンポーネント採用によりコードの変更点が多くなりました。
本記事では、私が個人的に運用している小規模サイトで、Next.js v12からv13へマイグレーションする中で加えたコードの変更を箇条書きで紹介します。
なお、本記事よりも細かくAppフォルダ導入による変更点を知りたい方は下記記事をご覧ください。
Next.jsバージョン13で導入されたAppフォルダを使った最新のNext.js開発に興味のある方は、今月(2023年6月)リリースした下記書籍を参考にしてください。
はじめてつくるNext.jsサイト
【最新バージョンのNext.jsとAppフォルダで、時短でNext.jsを習得】
1759円 → 0円
Next.js v13でパス取得
従来は次のように書いていました。
import { useRouter } from "next/router"
const Hello = () => {
const router = useRouter()
console.log(router.asPath) // /blog/first-article
return(
<div>
...
Next.js v13では次のようになります。
import { usePathname } from "next/navigation"
const Hello = () => {
const pathname = usePathname()
console.log(pathname) // /blog/first-article
return(
<div>
...
Next.js v13でリダイレクト
従来は次のように書いていました。
import { useRouter } from "next/router"
const Hello = () => {
const router = useRouter()
router.push("/success")
router.replace("/success")
return(
<div>
...
Next.js v13では次のようになります。
import { useRouter } from "next/navigation"
const Hello = () => {
const router = useRouter()
router.push("/success")
OR
router.replace("/success")
return(
<div>
...
Next.js v13のAPIルート
従来は次のように書いていました。
/pages/api/hello.js
export default function hello(req, res){
return res.json("Hello!")
}
Next.js v13ではAppフォルダに合わせてフォルダ構成とコードが変わり、次のようになります。
/app/api/hello/route.js
import { NextResponse } from "next/server"
export async function GET(request) {
return NextResponse.json("Hello!")
}
Next.js v13でリクエストbodyを解析
従来は次のように書いていました。
/pages/api/hello.js
export default function hello(req, res){
console.log(req.body) // リクエストbodyの中身が表示
return res.json("こんにちは")
}
Next.js v13では次のようになります。
/app/api/hello/route.js
import { NextResponse } from "next/server"
export async function POST(request) {
const reqBody = await request.json()
console.log(reqBody) // リクエストbodyの中身が表示
return NextResponse.json("Hello!")
}