Progressively Enhance Handling Your Forms With React.js Server Actions
Progressively Enhance Handling Your Forms With React.js Server Actions
By Dave Bitter
6 min read
A large part of adding interactivity to your applications is through forms. Single Page Applications SPAs have not always handled this part the best. Let’s have a look at how we can use React.js Server Actions to handle your forms progressively enhanced.
- Authors
- Name
- Dave Bitter
- linkedinDave Bitter
- twitter@dave_bitter
- Github
- githubDaveBitter
- Website
- websiteBlog
The issue with the rise of SPAs in the past
When we moved to SPAs in the past we introduced a big issue to our web applications. It didn’t work without JavaScript. Whilst this has been disregarded by many as “our users run the JavaScript on their device”, there is a serious fault in this view.
As Jake Archibald pointed out (back in 2012!), there is a variety of situations where your JavaScript is not available to the user. It may not have been downloaded yet, your CDN might be down and more.
Frameworks like Next.js render your React.js web applications on the server so it will at least render the HTML. Regardless of whether your client-side JavaScript loads, the user will still be able to view the information on the page. This is a must-have feature as before, you would simply see a white page if the React.js bundle did not load.
For some reason, developers seem to think that now we use server-side rendering, our applications are good enough. For static pages without much user interaction, this may be true, but as soon as there is input required from the user, these pages fully rely on the client-side JavaScript. Why is this?
As with SPAs, we just had an empty static HTML file where a JavaScript bundle would inject the whole web application, there was no way of handling a form request. There was no server to handle it. So what did we do? We created a separate API where we would be able to receive and handle requests made from our front end. The added benefit is the performance of not having a full page reload as well. In our front-end, we would intercept the submit event of the form element, gather the data, create the request and finally submit it to our API. In practice, I even saw that developers stopped using the form element altogether as they had no real use for it anymore. Instead, we ended up with a bunch of client-side state to hold the latest data the user inputted and even more to sanitize, validate and send over this data. What a shame!
Using the web platform instead of fighting against it
The big issue I noticed was how much we were fighting against the web as a platform. The web has a standardized way to work with sending over data to a server. Forms! So why would we so actively prevent the default behaviour and implement our own way?
Well, we kind of had to. SPA frameworks were designed to just be a thing static layer that makes requests to APIs. Remember the term Jamstack? Whilst this had advantages like, for instance, making it easier to deploy and work on, it also brought the downsides I mentioned before.
As frameworks like Next.js got popular, we’ve solved the server-side rendering issue of our web applications, but never really focused on the form handling issues. The first time I used a real solution for this was back when I looked into Remix. They provided an elegant way for developers to not just handle forms, but handle them progressively enhanced.
In essence, this approach is simple. Start with making sure you offer a solution that will work for every user. Next, when more functionality is available for the users, enhance the user experience. In the case of forms, being able to submit them to a back-end without the need for any client-side JavaScript. Then, when it is available, handle the request client-side and update the UI.
In my opinion, Remix action functions handle this very well. It offers developers the tools to make it easy to work with the platform and it will make sure to optimize the user experience once client-side JavaScript is available. But providing developers with the tools to work with the web platform shouldn’t be up to Remix, this should already be possible in React.js itself.
React.js Server Actions
The React.js team has been working hard on server-side React.js for the past years. Next to being able to render your components server-side using React.js Server Components, we are finally getting a way in React.js to handle forms on the server properly!
Imagine this form in your React.js web application:
With just the HTML and CSS for this form, the browser will try to submit this to the back-end where no server is handling this POST request. The browser will reload the page and the submitted form data will be in the URL as query parameters:
So what do you do as a developer? You listen for the handle submit event and call preventDefault
on the submit event to handle it yourself:
// page.js
import { useRouter } from 'next/navigation'
export default function Page() {
const router = useRouter()
const handleSubmit = (event) => {
event.preventDefault()
const formData = new FormData(event.target)
const data = Object.fromEntries(formData)
// Do something with data. Most likely, send it to the server using fetch
// Redirect the user to the new page
router.push('/thank-you')
}
return <form onSubmit={handleSubmit}>...</form>
}
Oh no! Our page is now fully reliant on client-side JavaScript. This is how quickly these things sneak in. So what if we can pass a server-side React.js function to the form to handle the actual form POST request? First, we create an action.js
file with the "use server"
directive where we export our server-side function that handles the form submission.
// actions.js
'use server'
import { redirect } from 'next/navigation'
export async function handleSubmit(formData) {
const data = Object.fromEntries(formData)
// Do something with data. Most likely, store it in your database
// Redirect the user to the new page
redirect('/thank-you')
}
Then, we use that as the callback for the action attribute on the form.
// page.js
import { handleSubmit } from './submit.js'
export default function Page() {
return <form action={handleSubmit}>...</form>
}
That’s it, by slightly altering the way we handle the form, we can now make use of React.js Server Actions and provide Progressive Enhancement out of the box!
Once stable, make this the standard
React.js Server Actions are coming with the upcoming release of React.js 19. You can already use it from Next.js 14. We finally have a solid solution to handling forms in React.js. Make sure to spend an afternoon learning how to use this. Besides handling basic form requests, there are a few other features to improve the user experience surrounding forms. Make sure to read up on these resources to get an overview of what is possible:
- React.js Server Actions: https://react.dev/reference/react/use-server
- Next.js Server Actions: https://nextjs.org/docs/app/api-reference/next-config-js/serverActions
Upcoming events
Coven of Wisdom - Herentals - Winter `24 edition
Worstelen jij en je team met automated testing en performance? Kom naar onze meetup waar ervaren sprekers hun inzichten en ervaringen delen over het bouwen van robuuste en efficiënte applicaties. Schrijf je in voor een avond vol kennis, heerlijk eten en een mix van creativiteit en technologie! 🚀 18:00 – 🚪 Deuren open 18:15 – 🍕 Food & drinks 19:00 – 📢 Talk 1 20:00 – 🍹 Kleine pauze 20:15 – 📢 Talk 2 21:00 – 🙋♀️ Drinks 22:00 – 🍻 Tot de volgende keer? Tijdens deze meetup gaan we dieper in op automated testing en performance. Onze sprekers delen heel wat praktische inzichten en ervaringen. Ze vertellen je hoe je effectieve geautomatiseerde tests kunt schrijven en onderhouden, en hoe je de prestaties van je applicatie kunt optimaliseren. Houd onze updates in de gaten voor meer informatie over de sprekers en hun specifieke onderwerpen. Over iO Wij zijn iO: een groeiend team van experts die end-to-end-diensten aanbieden voor communicatie en digitale transformatie. We denken groot en werken lokaal. Aan strategie, creatie, content, marketing en technologie. In nauwe samenwerking met onze klanten om hun merken te versterken, hun digitale systemen te verbeteren en hun toekomstbestendige groei veilig te stellen. We helpen klanten niet alleen hun zakelijke doelen te bereiken. Samen verkennen en benutten we de eindeloze mogelijkheden die markten in constante verandering bieden. De springplank voor die visie is talent. Onze campus is onze broedplaats voor innovatie, die een omgeving creëert die talent de ruimte en stimulans geeft die het nodig heeft om te ontkiemen, te ontwikkelen en te floreren. Want werken aan de infinite opportunities van morgen, dat doen we vandaag.
| Coven of Wisdom Herentals
Go to page for Coven of Wisdom - Herentals - Winter `24 editionMastering Event-Driven Design
PLEASE RSVP SO THAT WE KNOW HOW MUCH FOOD WE WILL NEED Are you and your team struggling with event-driven microservices? Join us for a meetup with Mehmet Akif Tütüncü, a senior software engineer, who has given multiple great talks so far and Allard Buijze founder of CTO and founder of AxonIQ, who built the fundaments of the Axon Framework. RSVP for an evening of learning, delicious food, and the fusion of creativity and tech! 🚀 18:00 – 🚪 Doors open to the public 18:15 – 🍕 Let’s eat 19:00 – 📢 Getting Your Axe On Event Sourcing with Axon Framework 20:00 – 🍹 Small break 20:15 – 📢 Event-Driven Microservices - Beyond the Fairy Tale 21:00 – 🙋♀️ drinks 22:00 – 🍻 See you next time? Details: Getting Your Axe On - Event Sourcing with Axon Framework In this presentation, we will explore the basics of event-driven architecture using Axon Framework. We'll start by explaining key concepts such as Event Sourcing and Command Query Responsibility Segregation (CQRS), and how they can improve the scalability and maintainability of modern applications. You will learn what Axon Framework is, how it simplifies implementing these patterns, and see hands-on examples of setting up a project with Axon Framework and Spring Boot. Whether you are new to these concepts or looking to understand them more, this session will provide practical insights and tools to help you build resilient and efficient applications. Event-Driven Microservices - Beyond the Fairy Tale Our applications need to be faster, better, bigger, smarter, and more enjoyable to meet our demanding end-users needs. In recent years, the way we build, run, and operate our software has changed significantly. We use scalable platforms to deploy and manage our applications. Instead of big monolithic deployment applications, we now deploy small, functionally consistent components as microservices. Problem. Solved. Right? Unfortunately, for most of us, microservices, and especially their event-driven variants, do not deliver on the beautiful, fairy-tale-like promises that surround them.In this session, Allard will share a different take on microservices. We will see that not much has changed in how we build software, which is why so many “microservices projects” fail nowadays. What lessons can we learn from concepts like DDD, CQRS, and Event Sourcing to help manage the complexity of our systems? He will also show how message-driven communication allows us to focus on finding the boundaries of functionally cohesive components, which we can evolve into microservices should the need arise.
| Coven of Wisdom - Utrecht
Go to page for Mastering Event-Driven DesignThe Leadership Meetup
PLEASE RSVP SO THAT WE KNOW HOW MUCH FOOD WE WILL NEED What distinguishes a software developer from a software team lead? As a team leader, you are responsible for people, their performance, and motivation. Your output is the output of your team. Whether you are a front-end or back-end developer, or any other discipline that wants to grow into the role of a tech lead, RSVP for an evening of learning, delicious food, and the fusion of leadership and tech! 🚀 18:00 – 🚪 Doors open to the public 18:15 – 🍕 Let’s eat 19:00 – 📢 First round of Talks 19:45 – 🍹 Small break 20:00 – 📢 Second round of Talks 20:45 – 🙋♀️ drinks 21:00 – 🍻 See you next time? First Round of Talks: Pixel Perfect and Perfectly Insane: About That Time My Brain Just Switched Off Remy Parzinski, Design System Lead at Logius Learn from Remy how you can care for yourself because we all need to. Second Round of Talks: Becoming a LeadDev at your client; How to Fail at Large (or How to Do Slightly Better) Arno Koehler Engineering Manager @ iO What are the things that will help you become a lead engineer? Building Team Culture (Tales of trust and positivity) Michel Blankenstein Engineering Manager @ iO & Head of Technology @ Zorggenoot How do you create a culture at your company or team? RSVP now to secure your spot, and let's explore the fascinating world of design systems together!
| Coven of Wisdom - Amsterdam
Go to page for The Leadership Meetup