Simplify your stack and build anything. Or everything.
Build tomorrow’s web with a modern solution you truly own.
Code-based nature means you can build on top of it to power anything.
It’s time to take back your content infrastructure.

Using Local API Operations with Server Functions

In Next.js, server functions (previously called server actions) are special functions that run exclusively on the server, enabling secure backend logic execution while being callable from the frontend. These functions bridge the gap between client and server, allowing frontend components to perform backend operations without exposing sensitive logic.

Why Use Server Functions?

  • Executing Backend Logic from the Frontend: The Local API is designed for server environments and cannot be directly accessed from client-side code. Server functions enable frontend components to trigger backend operations securely.
  • Security Benefits: Instead of exposing a full REST or GraphQL API, server functions restrict access to only the necessary operations, reducing potential security risks.
  • Performance Optimizations: Next.js handles server functions efficiently, offering benefits like caching, optimized database queries, and reduced network overhead compared to traditional API calls.
  • Simplified Development Workflow: Rather than setting up full API routes with authentication and authorization checks, server functions allow for lightweight, direct execution of necessary operations.

When to Use Server Functions

Use server functions whenever you need to call Local API operations from the frontend. Since the Local API is only accessible from the backend, server functions act as a secure bridge, eliminating the need to expose additional API endpoints.

Examples

All Local API operations can be used within server functions, allowing you to interact with Payload's backend securely.

For a full list of available operations, see the Local API overview.

In the following examples, we'll cover some common use cases, including:

  • Creating a document
  • Updating a document
  • Handling file uploads when creating or updating a document
  • Authenticating a user

Creating a Document

First, let's create our server function. Here are some key points for this process:

  • Begin by adding 'use server' at the top of the file.
  • You can still use utilities such as getPayload().
  • Once the function structure is in place, call the Local API operation payload.create() and pass in the relevant data.
  • It's good practice to wrap this in a try...catch block for error handling.
  • Finally, make sure to return the created document (don't just run the operation).
1
'use server'
2
3
import { getPayload } from 'payload'
4
import config from '@payload-config'
5
6
export async function createPost(data) {
7
const payload = await getPayload({ config })
8
9
try {
10
const post = await payload.create({
11
collection: 'posts',
12
data,
13
})
14
return post
15
} catch (error) {
16
throw new Error(`Error creating post: ${error.message}`)
17
}
18
}

Now, let's look at how to call the createPost function we just created from the frontend in a React component when a user clicks a button:

1
'use client';
2
3
import React, { useState } from 'react';
4
import { createPost } from '../server/actions'; // import the server function
5
6
export const PostForm: React.FC = () => {
7
const [result, setResult] = useState<string>('');
8
9
return (
10
<>
11
<p>{result}</p>
12
13
<button
14
type="button"
15
onClick={async () => {
16
// Call the server function
17
const newPost = await createPost({ title: 'Sample Post' });
18
setResult('Post created: ' + newPost.title);
19
}}
20
>
21
Create Post
22
</button>
23
</>
24
);
25
};

Updating a Document

The key points from the previous example also apply here.

To update a document instead of creating one, you would use payload.update() with the relevant data and passing the document ID.

Here's how the server function would look:

1
'use server'
2
3
import { getPayload } from 'payload'
4
import config from '@payload-config'
5
6
export async function updatePost(id, data) {
7
const payload = await getPayload({ config })
8
9
try {
10
const post = await payload.update({
11
collection: 'posts',
12
id, // the document id is required
13
data,
14
})
15
return post
16
} catch (error) {
17
throw new Error(`Error updating post: ${error.message}`)
18
}
19
}

Here is how you would call the updatePost function from a frontend React component:

1
'use client';
2
3
import React, { useState } from 'react';
4
import { updatePost } from '../server/actions'; // import the server function
5
6
export const UpdatePostForm: React.FC = () => {
7
const [result, setResult] = useState<string>('');
8
9
return (
10
<>
11
<p>{result}</p>
12
13
<button
14
type="button"
15
onClick={async () => {
16
// Call the server function to update the post
17
const updatedPost = await updatePost('your-post-id-123', { title: 'Updated Post' });
18
setResult('Post updated: ' + updatedPost.title);
19
}}
20
>
21
Update Post
22
</button>
23
</>
24
);
25
};

Authenticating a User

In this example, we will check if a user is authenticated using Payload's authentication system. Here's how it works:

  • First, we use the headers function from next/headers to retrieve the request headers.
  • Next, we pass these headers to payload.auth() to fetch the user's authentication details.
  • If the user is authenticated, their information is returned. If not, handle the unauthenticated case accordingly.

Here's the server function to authenticate a user:

1
'use server'
2
3
import { headers as getHeaders } from 'next/headers'
4
import config from '@payload-config'
5
import { getPayload } from 'payload'
6
7
export const authenticateUser = async () => {
8
const payload = await getPayload({ config })
9
const headers = await getHeaders()
10
const { user } = await payload.auth({ headers })
11
12
if (user) {
13
return { hello: user.email }
14
}
15
16
return { hello: 'Not authenticated' }
17
}

Here's a basic example of how to call the authentication server function from the frontend to test it:

1
'use client';
2
3
import React, { useState } from 'react';
4
5
import { authenticateUser } from '../server/actions'; // Import the server function
6
7
export const AuthComponent: React.FC = () => {
8
const [userInfo, setUserInfo] = useState<string>('');
9
10
11
return (
12
<React.Fragment>
13
<p>{userInfo}</p>
14
15
<button
16
onClick={async () => {
17
// Call the server function to authenticate the user
18
const result = await authenticateUser();
19
setUserInfo(result.hello);
20
}}
21
type="button"
22
>
23
Check Authentication
24
</button>
25
</React.Fragment>
26
);
27
};

Creating a Document with File Upload

This example demonstrates how to write a server function that creates a document with a file upload. Here are the key steps:

  • Pass two arguments: data for the document content and upload for the file
  • Merge the upload file into the document data as the media field
  • Use payload.create() to create a new post document with both the document data and file
1
'use server'
2
3
import { getPayload } from 'payload'
4
import config from '@payload-config'
5
6
export async function createPostWithUpload(data, upload) {
7
const payload = await getPayload({ config })
8
9
try {
10
// Prepare the data with the file
11
const postData = {
12
...data,
13
media: upload,
14
}
15
16
const post = await payload.create({
17
collection: 'posts',
18
data: postData,
19
})
20
21
return post
22
} catch (error) {
23
throw new Error(`Error creating post: ${error.message}`)
24
}
25
}

Here is how you would use the server function we just created in a frontend component to allow users to submit a post along with a file upload:

  • The user enters the post title and selects a file to upload.
  • When the form is submitted, the handleSubmit function checks if a file has been chosen.
  • If a file is selected, it passes both the title and the file to the createPostWithFile server function.
  • And you are done!
1
'use client';
2
3
import React, { useState } from 'react';
4
import { createPostWithUpload } from '../server/actions';
5
6
export const PostForm: React.FC = () => {
7
const [title, setTitle] = useState<string>('');
8
const [file, setFile] = useState<File | null>(null);
9
const [result, setResult] = useState<string>('');
10
11
const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
12
if (e.target.files) {
13
setFile(e.target.files[0]);
14
}
15
};
16
17
const handleSubmit = async (e: React.FormEvent) => {
18
e.preventDefault();
19
if (!file) {
20
setResult('Please upload a file.');
21
return;
22
}
23
24
try {
25
// Call the server function to create the post with the file
26
const newPost = await createPostWithUpload({ title }, file);
27
setResult('Post created with file: ' + newPost.title);
28
} catch (error) {
29
setResult('Error: ' + error.message);
30
}
31
};
32
33
return (
34
<form onSubmit={handleSubmit}>
35
<input
36
type="text"
37
value={title}
38
onChange={(e) => setTitle(e.target.value)}
39
placeholder="Post Title"
40
/>
41
<input type="file" onChange={handleFileChange} />
42
<button type="submit">Create Post</button>
43
<p>{result}</p>
44
</form>
45
);
46
};

Reusable Payload Server Functions

Managing authentication with the Local API can be tricky as you have to handle cookies and tokens yourself, and there aren't built-in logout or refresh functions since these only modify cookies. To make this easier, we provide login, logout, and refresh as ready-to-use server functions. They take care of the underlying complexity so you don't have to.

Login

Logs in a user by verifying credentials and setting the authentication cookie. This function allows login via username or email, depending on the collection auth configuration.

Importing the login function

1
import { login } from '@payloadcms/next/auth'

The login function needs your Payload config, which cannot be imported in a client component. To work around this, create a simple server function like the one below, and call it from your client.

1
'use server'
2
3
import { login } from '@payloadcms/next/auth'
4
import config from '@payload-config'
5
6
export async function loginAction({
7
email,
8
password,
9
}: {
10
email: string
11
password: string
12
}) {
13
try {
14
const result = await login({
15
collection: 'users',
16
config,
17
email,
18
password,
19
})
20
return result
21
} catch (error) {
22
throw new Error(
23
`Login failed: ${error instanceof Error ? error.message : 'Unknown error'}`,
24
)
25
}
26
}

Login from the React Client Component

1
'use client'
2
3
import { useState } from 'react'
4
import { loginAction } from '../loginAction'
5
6
export default function LoginForm() {
7
const [email, setEmail] = useState<string>('')
8
const [password, setPassword] = useState<string>('')
9
10
return (
11
<form onSubmit={() => loginAction({ email, password })}>
12
<label htmlFor="email">Email</label>
13
<input
14
id="email"
15
onChange={(e: ChangeEvent<HTMLInputElement>) =>
16
setEmail(e.target.value)
17
}
18
type="email"
19
value={email}
20
/>
21
<label htmlFor="password">Password</label>
22
<input
23
id="password"
24
onChange={(e: ChangeEvent<HTMLInputElement>) =>
25
setPassword(e.target.value)
26
}
27
type="password"
28
value={password}
29
/>
30
<button type="submit">Login</button>
31
</form>
32
)
33
}

Logout

Logs out the current user by clearing the authentication cookie.

Importing the logout function

1
import { logout } from '@payloadcms/next/auth'

Similar to the login function, you now need to pass your Payload config to this function and this cannot be done in a client component. Use a helper server function as shown below.

1
'use server'
2
3
import { logout } from '@payloadcms/next/auth'
4
import config from '@payload-config'
5
6
export async function logoutAction() {
7
try {
8
return await logout({ config })
9
} catch (error) {
10
throw new Error(
11
`Logout failed: ${error instanceof Error ? error.message : 'Unknown error'}`,
12
)
13
}
14
}

Logout from the React Client Component

1
'use client'
2
3
import { logoutAction } from '../logoutAction'
4
5
export default function LogoutButton() {
6
return <button onClick={() => logoutFunction()}>Logout</button>
7
}

Refresh

Refreshes the authentication token for the logged-in user.

Importing the refresh function

1
import { refresh } from '@payloadcms/next/auth'

As with login and logout, you need to pass your Payload config to this function. Create a helper server function like the one below. Passing the config directly to the client is not possible and will throw errors.

1
'use server'
2
3
import { refresh } from '@payloadcms/next/auth'
4
import config from '@payload-config'
5
6
export async function refreshAction() {
7
try {
8
return await refresh({
9
collection: 'users', // pass your collection slug
10
config,
11
})
12
} catch (error) {
13
throw new Error(
14
`Refresh failed: ${error instanceof Error ? error.message : 'Unknown error'}`,
15
)
16
}
17
}

Using Refresh from the React Client Component

1
'use client'
2
3
import { refreshAction } from '../actions/refreshAction'
4
5
export default function RefreshTokenButton() {
6
return <button onClick={() => refreshFunction()}>Refresh</button>
7
}

Error Handling in Server Functions

When using server functions, proper error handling is essential to prevent unhandled exceptions and provide meaningful feedback to the frontend.

Best Practices

  • Wrap Local API calls in try/catch blocks to catch potential errors.
  • Log errors on the server for debugging purposes.
  • Return structured error responses instead of exposing raw errors to the frontend.

Example of good error handling:

1
export async function createPost(data) {
2
try {
3
const payload = await getPayload({ config })
4
return await payload.create({ collection: 'posts', data })
5
} catch (error) {
6
console.error('Error creating post:', error)
7
return { error: 'Failed to create post' }
8
}
9
}

Security Considerations

Using server functions helps prevent direct exposure of Local API operations to the frontend, but additional security best practices should be followed:

Best Practices

  • Restrict access: Ensure that sensitive actions (like user management) are only callable by authorized users.
  • Avoid passing sensitive data: Do not return sensitive information such as user data, passwords, etc.
  • Use authentication & authorization: Check user roles before performing actions.

Example of restricting access based on user role:

1
export async function deletePost(postId, user) {
2
if (!user || user.role !== 'admin') {
3
throw new Error('Unauthorized')
4
}
5
6
const payload = await getPayload({ config })
7
return await payload.delete({ collection: 'posts', id: postId })
8
}
Next

Respecting Access Control with Local API Operations