oRPC is currently pre-stable, please report any issues on our Discord or GitHub 🚧
oRPC
background

Server Actions

Leverage oRPC for type-safe and powerful server actions

Server Actions in oRPC allow you to define type-safe server-side procedures that can be seamlessly invoked from client applications. To enable a procedure as a server action, you need to call the .actionable() method.

Basic Usage

To make a procedure compatible with server actions, use .actionable() as shown below:

'use server'
 
import {  } from '@orpc/server'
import {  } from 'zod'
 
export const  = 
  .(.({
    : .(),
  }))
  .(.())
  .(async ({  }) => {
    return `Hello ${.}`
  })
  .()
 
// from client just call it as a function
const  = async () => {
  const  = await ({ : 'Unnoq' })
  ()
}

Passing Context via .actionable()

When calling .actionable(), you can pass a context function that provides additional information for the procedure:

'use server'
 
import {  } from '@orpc/server'
import {  } from 'zod'
 
const  = .<{ : string }>()
 
export const  = 
  .(.({
    : .(),
  }))
  .(.())
  .(async ({ ,  }) => {
    // ^ context is fully typed
    return `Hello ${.}`
  })
  .({
    : async () => { // or just pass context directly
      return { : 'postgres' }
    },
  })

Using Middleware to Inject Context

Middleware can be used to inject context dynamically before the procedure is executed:

'use server'
 
import { ,  } from '@orpc/server'
import {  } from 'next/headers'
import {  } from 'zod'
 
const  = .(async ({  }) => {
  const  = await ()
  const  = .('Authorization') ? { : 'example' } : 
 
  if (!) {
    throw new ({ : 'UNAUTHORIZED' })
  }
 
  return ({
    : {
      ,
    },
  })
})
 
export const  = 
  .(.({
    : .(),
  }))
  .(.())
  .(async ({ ,  }) => {
    // ^ context is fully typed
    return `Hello ${.}`
  })
  .()

On this page