React Server Functions

JS
S
JavaScript

Server Functions (newer approach): Works in all types (SPA/SSR/SSG) Natural fit for SPAs - similar to traditional API calls but with better DX For SSR: helps with initial render + subsequent data fetching For SSG: useful for dynamic data after initial static render Server Components (RSC): Primarily designed for SSR Cannot be used in pure SPAs Changes fundamental architecture to server-first Better for reducing initial JS bundle size Key Point: The article argues that you don't need Server Components (RSC) to get server-side benefits. Server Functions provide a more flexible approach that works across all React application types while maintaining familiar client-first architecture. Choice depends on: Application type (SPA/SSR/SSG) Bundle size requirements Team familiarity with React patterns Infrastructure constraints

1Example: This is Next.js Server Actions syntax, which is their implementation of Server Functions.
2
3// app/actions.ts
4'use server' // This marks it as a Server Function
5
6export async function getUserData(userId: string) {
7  // This runs on server only
8  const user = await db.users.findUnique({
9    where: { id: userId }
10  })
11  return user
12}
13
14// app/page.tsx
15'use client'
16import { getUserData } from './actions'
17
18export default function Page() {
19  async function handleClick() {
20    const user = await getUserData('123')
21    console.log(user)
22  }
23
24  return <button onClick={handleClick}>Get User</button>
25}

Created on 1/28/2025