Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Next.jsでAPIキーを安全に扱う方法

Sponsored · Your Podcast. Everywhere. Effortlessly. Share. Educate. Inspire. Entertain. You do you. We'll handle the rest.
Avatar for yamatai12 yamatai12
December 12, 2025
19

 Next.jsでAPIキーを安全に扱う方法

Avatar for yamatai12

yamatai12

December 12, 2025
Tweet

More Decks by yamatai12

Transcript

  1. Next.jsのサーバーコンポーネント (2/2) //呟きに関する情報を表示するページ import LikeButton from "@/app/ui/like-button"; import { getTweet

    } from "@/lib/data"; export default async function Page({ params, }: { params: { id: string }; }) { const { id } = params; const tweet = await getTweet(id); // サーバーコンポーネントでのデータ取得 return ( <div> <main> <h1>{tweet.title}</h1> {/* LikeButton から Server Action を呼んで “更新” する(mutation) */} <LikeButton tweetId={id} initialLikes={tweet.likes} /> {/* 従来のコンポーネント、stateやイベントハンドラー */} </main> </div> ); } 6
  2. サーバーアクションでのデータフェッチ (2/3) "use client"; import { useState, useTransition } from

    "react"; import { likeTweet } from "@/lib/actions"; export default function LikeButton({ tweetId, initialLikes, }: { tweetId: string; initialLikes: number; }) { const [likes, setLikes] = useState(initialLikes); const [isPending, startTransition] = useTransition(); return ( <button type="button" disabled={isPending} onClick={() => { startTransition(async () => { const nextLikes = await likeTweet(tweetId); // mutation(サーバーで更新) setLikes(nextLikes); }); }} ... 8
  3. サーバーアクションでのデータフェッチ (3/3) "use server"; import { incrementTweetLike, getTweet } from

    "@/lib/data"; // Server Action(mutation) export async function likeTweet(tweetId: string) { await incrementTweetLike(tweetId); // DB更新など(サーバー側) const tweet = await getTweet(tweetId); // 更新後の値を返す(簡易) return tweet.likes; } 9