0
0

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] server-onlyとuse server(server action)の違いと使い分け

Last updated at Posted at 2025-02-04

server-onlyとは?

処理がサーバーでのみ実行される保証をしたい。Server Componentでのみ利用可能にしたい時に有効。
client側では呼び出すことができず、build時にerrorとなります

例えば以下のコードはClient ComponentでもServer Componentでも含めることが可能ですが、process.env.API_KEYがprivateな環境変数であるため、Client Componentでは動作しません。

動作しないにも関わらずimportができてしまい、build時にerrorも発生しません。

import 'server-only'を追加することにより、開発者にServer Componentでのみ利用可能である意図を伝えるとともに、build時にerrorを出すことが可能です。

// 追加する
import 'server-only'

export async function getData() {
  const res = await fetch('https://external-service.com/data', {
    headers: {
      authorization: process.env.API_KEY,
    },
  })
 
  return res.json()
}

使用には追加のinstallが必要です

$ npm install server-only

server action

サーバー上で実行される非同期関数のこと
reactの"use server"ディレクトリを使って定義できる

  • 非同期(async)関数の先頭におくことで、関数をserver actionとしてマーク
  • 別のファイルの先頭に配置してそのファイルの全てのエクスポートをマーク
    インライン(関数の中の非同期関数をserver actionとするには1つ目の方法)
    クライアントコンポーネントで呼び出して利用するには、2を使う
export default function Page() {
  // Server Action
  async function create() {
    'use server'
    // Mutate data
  }
 
  return '...'
}

client componentからもserver actionが利用できるのは嬉しいですね
そして何より嬉しい点は、formのaction要素からも実行できる点です。 これによりformのstate管理が不要になります
server actionをformで使う例

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?