resolving cloudflare server actions 405 error in next.js

next.js server actions are powerful, but using them with cloudflare pages can be tricky. let’s tackle the 405 (method not allowed) error and get your server actions working smoothly, including accessing environment variables.

the problem

when implementing server actions on cloudflare pages, you might encounter a 405 error. this typically happens because cloudflare’s edge runtime doesn’t support the default next.js server action setup.

the solution

the key is to use the edge runtime for your page, separate your client-side form into its own component, and use the correct method to access environment variables.

implementation

first, let’s update our server action to include environment variable access:

app/actions/myAction.ts
'use server'
import { getRequestContext } from "@cloudflare/next-on-pages";
export async function myAction(formData: FormData) {
const context = getRequestContext();
const secretKey = context.env.MY_SECRET_KEY;
console.log('action called', formData.get('input')?.toString());
console.log('secret key:', secretKey);
return { message: "Action successful", secretKey };
}

next, create a client component for your form:

app/components/MyForm.tsx
'use client'
import { myAction } from '../actions/myAction'
import { useState } from 'react'
export default function MyForm() {
const [result, setResult] = useState<string | null>(null);
async function handleSubmit(formData: FormData) {
const result = await myAction(formData);
setResult(JSON.stringify(result));
}
return (
<form action={handleSubmit}>
<input name="input" type="text" />
<button type="submit">Submit</button>
{result && <p>Result: {result}</p>}
</form>
)
}

finally, use the edge runtime in your page component:

app/page.tsx
import MyForm from './components/MyForm'
export const runtime = 'edge'
export default function Page() {
return <MyForm />
}

get envvar in action

to access environment variables in your server action when using cloudflare pages, you need to use the getRequestContext function from @cloudflare/next-on-pages. this allows you to access the env object, which contains your environment variables.

here’s how it works:

  1. import the getRequestContext function
  2. call it within your server action to get the context
  3. access environment variables through context.env

this method ensures you can securely access your environment variables, including secrets, within your server actions.

considerations

key takeaways

  1. use the edge runtime for your page component
  2. separate your form into a client component
  3. use getRequestContext to access environment variables in server actions
  4. keep your server action logic simple and focused

by following these steps, you should be able to resolve the 405 error, use server actions effectively with cloudflare pages and next.js, and securely access your environment variables.