Server actions were added in NextJs 13.4 and they allow us to run server code without having to create a dedicated API endpoint.
Let's see how we can build a simple NextJs app that reads a value parameter from an HTML form and makes a call to an API.
First, we will need to enable server actions in next.config.js
file, as for the moment they are an experimental feature:
// next.config.js
const nextConfig = {
experimental: {
serverActions: true
}
}
module.exports = nextConfig
Now as the NextJs server actions are enabled we can add the use server
directive to a function to mark it as a server action:
// src/app/page.js
const api = 'https://jsonplaceholder.typicode.com/'
export default function Home() {
const fetchData = async (formData)=> {
'use server'
const itemsType = formData.get('items-type')
const response = await fetch(api + itemsType)
const data = await response.json()
console.log(data)
}
return (
<form action={fetchData}>
<select name="items-type">
<option value="posts">📰 Posts</option>
<option value="users">👨 Users</option>
{/* more options here */}
</select>
<button>Go get the data</button>
</form>
)
}
The above page will read the value of the items-type
form input and then will call the JSON Placeholder API with that parameter.
Some notes on this code:
- the
fetchData()
server action function needs to be marked async
even if it does not do an asynchronous operation
- given that this runs on the server, the data will be logged in the Node backend console
- before having access to the server actions this will not have been possible as we would have got an Event handlers cannot be passed to Client Component NextJs error
- while using server actions be very careful as they can make credential leaking very easy given that the line between server and client code gets very narrow
- do not use yet server actions in production. For the moment they are an experimental feature
You can browse the full code of the example on GitHub.
The post NextJs 13 server actions fetching data with form parameter appeared first on Js Craft.