LoginSignup
5
5

Next.jsを使ったAPI開発

Last updated at Posted at 2023-10-26

はじめに

Next.jsでAPIの開発をできるがあるので、メモ代わりに書いていきます。

Next.jsにおけるAPI開発とは

Next.jsはReactのフレームワークになりますが、APIを作成して、同じコードベースの中で、フロントエンドとバックエンドのコードを書くことができ、呼び出すことができます。Node.jsなどを使ってサーバを立てなくても、DBにアクセスできたりすることができるということです。

基本的なフォルダ構成

今回はApp Routerを使用していきます。
基本的には、apiフォルダを作成して、その中にファイルを追加して、APIのコードを書いていくことができます。そして、そのディレクトリ名と、ファイル名がAPIのエンドポイントになります。

サンプルコード

ドキュメントに沿って、簡単なAPIを作ります。
まずは、以下のコードを/api/router.jsに書いていきます。

/api/route.js
import { NextResponse } from "next/server";

export async function GET() {
  return NextResponse.json({
    message: "データを取得!",
  });
}

そしてこのコードをフロントエンドから呼び出してみましょう。
以下のコードを書きます。

page.tsx
"use client";

import axios from "axios";

export default function Home() {
  const getData = async () => {
    const response = await axios.get("/api");
    console.log(response);
  };

  return (
    <main className="flex min-h-screen flex-col items-center justify-between p-24">
      <div className="z-10 max-w-5xl w-full items-center justify-between font-mono text-sm lg:flex">
        <button
          className="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded"
          onClick={getData}
        >
          getDate
        </button>
      </div>
    </main>
  );
}

すると、以下のように/api/route.jsに作成したデータが取得できました!

スクリーンショット 2023-10-26 23.12.14.png

次は、apiのエンドポイントを「/api/users」としてみましょう。
usersディレクトリをapiディレクトリ配下に作り、その中にrouter.jsを作り、以下のようなコード書いていきます。

/api/users/route.js
import { NextResponse } from "next/server";

export async function GET() {
  return NextResponse.json({
    message: "/api/usersからデータを取得!",
  });
}

フロントエンド側のコードは以下のようになります。

page.tsx
"use client";

import axios from "axios";

export default function Home() {
  const getData = async () => {
    const response = await axios.get("/api/users");
    console.log(response);
  };

  return (
    <main className="flex min-h-screen flex-col items-center justify-between p-24">
      <div className="z-10 max-w-5xl w-full items-center justify-between font-mono text-sm lg:flex">
        <button
          className="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded"
          onClick={getData}
        >
          getDate
        </button>
      </div>
    </main>
  );
}

すると以下のように、データを取得できました!
スクリーンショット 2023-10-27 9.04.15.png

ドキュメント

以下が参考にしたドキュメントです。

最後に

以上がNext.jsを使ったAPI開発をしていきました。
今回は、App Routerを使いましたが、Page RouterとApp Routerでは作り方が違うので注意が必要になります。

他にも色々な記事を書いているので、よければ読んでいってください、、、

5
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
5