body {
font-family: Arial, sans-serif;
line-height: 1.6;
margin: 2em;
}
h1 {
text-align: center;
}
p {
margin-bottom: 1em;
}
Next.js 14 Server Actions – Complete Guide
Next.js 14 comes with enhanced server actions for GET, POST, and DELETE requests. It also includes error handling, notification, and loader features for a seamless server-side development experience. In this complete guide, we’ll cover how to use these features in your Next.js applications.
GET Requests
To make a GET request in Next.js 14, you can use the fetch
API or the axios
library to fetch data from a server. Here’s an example using fetch
:
fetch('/api/data')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
POST Requests
For POST requests, you can use the same fetch
API or axios
library to send data to the server. Here’s an example using fetch
:
fetch('/api/data', {
method: 'POST',
body: JSON.stringify({ name: 'John' }),
headers: {
'Content-Type': 'application/json'
}
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
DELETE Requests
To send a DELETE request, you can also use the fetch
API or axios
library. Here’s an example using fetch
:
fetch('/api/data/1', {
method: 'DELETE'
})
.then(response => console.log('Deleted'))
.catch(error => console.error('Error:', error));
Error Handling
Next.js 14 provides built-in error handling for server actions. You can use try...catch
blocks or .catch()
methods to handle errors in your server-side code. Here’s an example using fetch
with error handling:
try {
const response = await fetch('/api/data');
const data = await response.json();
console.log(data);
} catch (error) {
console.error('Error:', error);
}
Notification
Next.js 14 also includes a built-in notification system for server actions. You can use this to display success or error messages to the user. Here’s an example using a notification library like react-toastify
:
import { toast } from 'react-toastify';
// Display success message
toast.success('Data saved successfully!');
// Display error message
toast.error('Error saving data.');
Loader
For asynchronous server actions, you can use a loader to indicate to the user that something is happening in the background. Here’s an example using a spinner component:
import Spinner from 'react-spinner';
// Display loader while fetching data
<Spinner />
I like your Videos, keep continuing..
Thanks !
you should make video about dynamic routing