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?

【実践編】今すぐ使えるAI技術の最先端プラットフォーム完全ガイド| [第6回] Next.jsを活用したAIフロントエンドアプリの構築

Posted at

近年、AI技術の進化に伴い、ユーザーフレンドリーなインターフェースを提供するAIフロントエンドの重要性が高まっています。Next.jsは、高速で柔軟なフロントエンド開発を可能にするReactベースのフレームワークであり、AIアプリケーションのUI/UXを向上させるのに最適です。本記事では、Next.jsを活用したAIフロントエンドアプリの構築について詳しく解説します。


1. Next.jsがAIフロントエンドに適している理由

Next.jsは以下の特徴を持ち、AIフロントエンド開発に最適です。

  • SSR(サーバーサイドレンダリング)対応: 初回ロードが速く、SEOにも優れる。
  • APIルート機能: バックエンドと連携しやすく、AIモデルの推論結果をフロントエンドに組み込みやすい。
  • 動的ルーティング: AIアプリのユーザー体験を向上させる。
  • Reactのエコシステムを活用: 強力なコンポーネント設計が可能。

まず、Next.jsの環境をセットアップしましょう。

npx create-next-app@latest ai-frontend --typescript
cd ai-frontend
npm install

2. AI APIとの連携

AIアプリのフロントエンドでは、バックエンドのAIモデルと連携するAPIが必要です。Next.jsのAPIルート機能を使って、シンプルなAI推論APIを作成します。

2.1. APIエンドポイントの作成

/pages/api/predict.ts に以下のコードを追加します。

import type { NextApiRequest, NextApiResponse } from 'next';

type Data = {
  prediction: number[];
};

export default function handler(
  req: NextApiRequest,
  res: NextApiResponse<Data>
) {
  const input = req.body.values;
  const prediction = input.map((num: number) => num * 2); // 仮のAI推論
  res.status(200).json({ prediction });
}

3. フロントエンドの実装

3.1. フォーム入力とAI予測結果の表示

Next.jsのuseStatefetchを活用して、ユーザーが入力したデータをAPIに送信し、予測結果を取得します。

/pages/index.tsx に以下のコードを追加します。

import { useState } from 'react';

export default function Home() {
  const [input, setInput] = useState('');
  const [prediction, setPrediction] = useState<number[]>([]);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    const res = await fetch('/api/predict', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ values: input.split(',').map(Number) }),
    });
    const data = await res.json();
    setPrediction(data.prediction);
  };

  return (
    <div className="container mx-auto p-8">
      <h1 className="text-2xl font-bold">AI予測アプリ</h1>
      <form onSubmit={handleSubmit} className="mt-4">
        <input
          type="text"
          value={input}
          onChange={(e) => setInput(e.target.value)}
          placeholder="数値をカンマ区切りで入力"
          className="border p-2 mr-2"
        />
        <button type="submit" className="bg-blue-500 text-white p-2">予測</button>
      </form>
      <div className="mt-4">
        <h2 className="text-xl">予測結果:</h2>
        <p>{prediction.join(', ')}</p>
      </div>
    </div>
  );
}

4. Next.jsの最適化とデプロイ

Next.jsアプリのパフォーマンスを最適化するために、以下の点を考慮します。

  • getServerSideProps を活用: サーバーサイドでデータを事前に取得し、ロード時間を短縮。
  • 画像最適化 (next/image): AIによる画像処理アプリでパフォーマンスを向上。
  • キャッシュ (revalidate 設定): APIのレスポンスを効率的に管理。

また、Next.jsアプリはVercelを使って簡単にデプロイできます。

npx vercel

デプロイ後、AIフロントエンドアプリを公開できます!


5. まとめ

本記事では、Next.jsを活用してAIフロントエンドアプリを構築する方法を解説しました。

Next.jsはSSRとAPIルート機能を活用できるため、AIアプリと相性が良い
AI APIと連携するシンプルなフロントエンドを構築できる
Vercelを使えば、簡単にデプロイ可能

Next.jsを使ったAIアプリ開発に興味がある方は、ぜひ試してみてください!

「LGTM」&コメントでフィードバックをお待ちしています!


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?