1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Next.jsでGemini APIを動かす最小限のセットアップ

Last updated at Posted at 2025-05-03

はじめに

個人開発しているアプリに生成AIを使いたかったのでGemini APIを動かしてみました。

早速やる

大まかな手順は以下になります

  1. API Keyの作成
  2. 実装
    • Next.jsのセットアップ
    • API Keyの設定
    • API実装
    • UI実装
  3. 動作確認

1. API Keyの作成

こちらのページから作成できます

2. 実装

Next.jsのセットアップ

以下のコマンドを使ってNext.jsをインストールしてください。インストール時に色々質問されますが今回は動かすのが目的なので適当で大丈夫です。

npx create-next-app@latest

API Keyの設定

ルートに.env.localファイルを作成して取得したAPI Keyを置きます。

.env.local
GEMINI_API_KEY=取得したKey

APIの実装

Next.jsのroute hundlersを使ってapiを作ります。app/api/gemini-api/route.tsを作成してください。ちなみに多くの記事では@google/generative-aiが使われていましたが、今回は最新の@google/genaiをインストールしました。(プレビュー版みたいですが)

import { GoogleGenAI } from "@google/genai";
import { NextResponse } from "next/server";

export async function POST(req: Request) {
    const { prompt_post } = await req.json();
    const ai = new GoogleGenAI({apiKey: process.env.GEMINI_API_KEY});

    const response = await ai.models.generateContent({
        model: "gemini-2.0-flash",
        contents: prompt_post,
      });
      
    return NextResponse.json({
        response: response.text,
    });
}

コードは以下のドキュメントを参考にしました

UI実装

入力したプロンプトをAPIに渡してAIの回答を取得・表示しています。

'use client';

import { useState } from 'react';

export default function GeminiTest() {
  const [prompt, setPrompt] = useState('');
  const [response, setResponse] = useState('');

  const handleClick = async () => {
    const res = await fetch('/api/gemini-api', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ prompt_post: prompt }),
    });
    const data = await res.json();
    setResponse(data.response);
  };

  return (
    <div>
      <input
        value={prompt}
        onChange={(e) => setPrompt(e.target.value)}
        placeholder="プロンプトを入力"
      />
      <button onClick={handleClick}>送信</button>
      <p>{response}</p>
    </div>
  );
}

3. 動作確認

良さそうです😊

スクリーンショット 2025-05-03 9.34.29.png

終わりに

取り急ぎ動かしただけでまだモデルや料金について把握できてないので色々調べてみようと思います。

参考

1
1
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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?