Next Sandbox

functions

The array of server actions.

Server Actions

Server Actions are special async functions that run on the server. They must include 'use server' at the top of their definition so Next.js can recognize and execute them correctly.

Defining Server Actions

Server actions can be defined in two ways:

Within the Same File

Define server actions directly above withSandbox, ensuring the 'use server' directive is placed at the top of each action:

app/sandbox/page.tsx
import { withSandbox } from 'next-sandbox';
 
const seedUsers = async () => {
  'use server'; 
 
  // Some db calls
};
 
export default withSandbox({
  functions: [
    {
      name: 'Seed Users',
      function: seedUsers,
    },
  ],
});

Importing from Another File

You can define server actions in separate files and import them where needed. Ensure the 'use server' directive is included at the top of the external file:

actions/users.ts
'use server'; 
 
export const seedUsers = async () => {
  // Some db calls
};

Then import the action:

app/sandbox/page.tsx
import { withSandbox } from 'next-sandbox';
import { seedUsers } from '@/actions/users'; 
 
export default withSandbox({
  functions: [
    {
      name: 'Seed Users',
      function: seedUsers,
    },
  ],
});

Avoid Inline Server Actions

Avoid defining server actions inline within functions, as this pattern is not supported and may cause unexpected behavior.

Incorrect usage example:

app/sandbox/page.tsx
import { withSandbox } from 'next-sandbox';
 
export default withSandbox({
  functions: [
    {
      name: 'Seed Users',
      function: async () => {
        'use server'; 
        // Some db calls
      }, 
    },
  ],
});

On this page