Next Sandbox

beforeRender

A function executes on the server before the page is rendered.

beforeRender()

An async function that runs on the server before rendering the UI, where you can perform authentication, permission checks, etc., is particularly useful when you want to run a sandbox page in a production environment.

Usage

You can directly pass the server logic to be executed in the beforeRender parameter, since withSandbox() renders a Server Component. This means your logic will run on the server before the Sandbox UI is rendered.

app/sandbox/page.tsx
import { auth } from '@/lib/auth';
import { withSandbox } from 'next-sandbox';
import { forbidden } from 'next/navigation';
 
export default withSandbox({
  beforeRender: async () => { 
    const user = await auth(); 
    if (user.role !== 'admin') { 
      forbidden(); 
    } 
  }, 
  // ...
});

Protect server actions

Due to server actions, Next.js allocates a separate POST endpoint for it at build time, which is unrelated to the beforeRender we define, as it only restricts the rendering of the UI. Therefore, the best practice is to also perform strict authentication within server actions, which ensures that even if someone directly accesses the server actions endpoint, they cannot execute it successfully.

On this page