Using Next.JS and Redux for Epic Noscript Web Apps

Rate this content
Bookmark

A short exploration of a method for building websites that work without JS, while still enjoying the convenience of modern frontend and backend technologies - with live coding!

21 min
25 Oct, 2021

Video Summary and Transcription

This Talk explores developing web applications that work without JavaScript enabled in the browser, while still enjoying the benefits of modern web technologies. The speaker demonstrates converting an existing application to work without JavaScript by wrapping buttons in a form and preventing the default submit event. React helpers are introduced to handle async actions and the speaker shows how to make a counter app work without JavaScript by removing unnecessary callbacks and changing buttons to a button component. The talk also covers adding a form and a surprise feature, and emphasizes that by leveraging forms and an event-based store, applications can seamlessly work with or without JavaScript.

Available in Español

1. Introduction to No-Script Web Apps

Short description:

In this talk, I will explore a method to develop applications that work without JavaScript enabled in the browser while still enjoying the benefits of modern web technologies. I will show you a TodoMEC application that works with and without JavaScript. There are several reasons why someone would disable JavaScript, including performance, fewer popups, faster load times, and increased security. I added making my wishlist service work without JavaScript to my task list because it's privacy-friendly and can function without JavaScript. However, I didn't know how to achieve this with Redux and server-side rendering.

Hi, my name is Daniel and I'm a web developer and a privacy enthusiast based in Oslo, Norway. Thank you for tuning in to this talk about using Next.js and Redux for epic no-script web apps, which will be a short exploration of a method that will enable you to develop applications that work without JavaScript enabled in the browser while still enjoying the benefits and convenience of modern web technologies when making them.

Right off the bat, I want to show you this. This is your standard TodoMEC application, where you can add stuff, edit stuff, check stuff off, filter them and clear them. And here it is again. And I want you to pay close attention and see if you can spot any difference. So we can add stuff, we can say whoops, and edit stuff, check off stuff, apply some filters and we can clear them. So, notice anything? Well, this last one was entirely without JavaScript in the browser. And what's so exciting is that this was both the exact same React application, the exact same HTML rendered to the DOM. And I find that pretty cool, that we can have one application that seamlessly works both with and without JavaScript.

But why would anyone disable JavaScript in the first place? Well, there are several reasons, actually. One of them is performance. When there's no JavaScript running in the background, then your computer has more resources to do other stuff. Another one is fewer popups. When you disable JavaScript, you don't have any of the pull screen newsletter signups or slides up from the bottom, scroll hogging or content that are suddenly applied to the website that makes the scrolling jump and stuff like that. You also have faster load times, as obviously you're not loading the JavaScript, so the page will load faster. And a contributing factor to that is that you're not loading the tracking scripts and the ad networks that in themselves aren't really wanted most of the time. Some users will also disable JavaScript because of increased security. There are examples in the past where ad networks have been used as an attack vector for browser vulnerabilities. And by disabling JavaScript, you avoid them and you also avoid stuff like cross-site scripting. I run a wishlist service called Wishigift. And back in 2018, I added this to the task list, make the site work without JavaScript. Because it's a privacy-friendly wishlist service, and I figure that maybe our most privacy-minded users would like to have an experience that works without JavaScript. And also it's nice to be able to post something on Hacker News without the comments saying that this doesn't work without JavaScript. But also because it's the kind of website that can work without JavaScript or perhaps even should, I don't have any WebGL experiences, or I'm not using any web APIs in a heavy way. It's basically a glorified CRUD application, as are many other applications. And I think that those kinds of websites that can work without JavaScript also should. But I had no idea how. I was using Redux for absolutely everything. And I also dabbled a bit in server-side rendering.

2. Converting App to Work Without JavaScript

Short description:

To convert an existing application to work without JavaScript, wrap buttons in a form and prevent the default submit event. If JavaScript is enabled, the event is prevented, and the action is dispatched client-side. If JavaScript is disabled, the request hits the server, and the server dispatches the action and re-renders the application server-side. The resulting state and HTML are the same in both scenarios.

So I just started some background processing. Asked myself, what's available when JavaScript is disabled? It's just HTML and CSS. Okay. How can I convert this already existing application to one that works without JavaScript? No idea. And how can I do it in a way that's maintainable? Because I didn't want to have two separate codebases that would need to be maintained.

Well, fast forward to 2020, and I think I wake up one day, and my mind has put some pieces together. I realized that one of the tenets of Redux, which is thou shalt only put serializable values in state or actions, goes very well with, or actually aligns perfectly with a certain type of payload that's also serializable. Well, talking about forms, the solution was there all along. Instead of having standalone buttons, I could simply wrap them in a form and prevent default on the submit so that if there was JavaScript enabled, the event would be prevented. And if there wasn't, well, it just hit the server and we can have our server dispatch whatever action that we want to perform.

So instead of having just a simple click handler on a button, instead we do something like this. We wrap it in a form and set the action to just an empty string so that when you submit this form, it's going to be sent to the same route that we're already at, which means a view route. And we make the assumption that the only reason why anyone would ever do a post request to a view routes is because they are submitting this kind of form that wraps an action that they want to perform. And inside it, we embed the current state or the client state, the app state and also the kind of action that we want to be dispatched. And we will replace our button type button with a submit button. And you can also omit the type attribute here.

Then in our app.js, if you're using Next.js that is, we have this get initial props, and we check for if this is a post request, well, then we want to read the body and the body will look something like this. It'll have an action type, for example, and the state. And we pass that along to a helper function. Now we'll parse the payload. Using the callback that we supplied, getReduxStore, it'll take the parsed state in the payload and create a new ReduxStore with that. And also dispatch the action in the payload to that ReduxStore and return the updated ReduxStore and the updated state. Then we can assign that to our preloaded state and re-render our application with that state.

So when JavaScript is enabled, user clicks the button, the event is prevented and the action is dispatched. State is updated and the React application re-renders client side. And it's quite similar when JavaScript is disabled, except that we can't prevent default. So the request will hit the server and our server will parse the payload and dispatch the action, get the updated state and re-render the React application server-side. And in both scenarios, the end result is the exact same. The state you end up with is exactly the same. And also, the HTML is exactly the same.

3. React Helpers and Handling Async Actions

Short description:

To help us with this, I've created some React helpers that I've added in an npm package. The most important component is the form component that embeds the state. It selects the state from the Redux and embeds it into the form. It also handles the submit by preventing defaulting on the client side and parsing the payload. We're serializing both the action and the payload into the form. We also have a button that wraps in the form component and passes along the necessary props. For async actions in a no-script scenario, we need to call and await the action creator instead of simply telling the server to dispatch an action.

To help us with this, I've created some React helpers that I've added in an npm package. And the most important component is the form component that embeds the state. It selects the state from the Redux and embeds it into the form. And also handles the submit. Which means preventing defaulting on the client side and parsing the payload. Because instead of just passing objects, we're actually typing out all the... We're serializing both the action and the payload into the form. So it parses the form payload and also dispatches any action contained within.

We also have a button, which is a simple helper that just takes a button and wraps it in the form component. And also passes along the necessary props. And you can find this on at witchy-gift.com. But I hear you. First of all, you were promising epic webapps. And second of all, how would you do it with async actions? Well, I got a solution for that as well. Who'da thunk?

So here we have a pretty simple application that enables you to search for epics. So we can search for Homer or we can just do an empty search and list all the epics on the project Gutenberg. And so client-side, this is talking with a third party API called Gutendex. You can see we have this spinner and stuff, and you can also see in the top right here, we have an indicator saying if this page was loaded on a GET request or a POST request. Now, in a no-script scenario, instead of simply telling the server to dispatch an action, that wouldn't do. It wouldn't suffice because we're having async actions. So we actually need to call and await the action creator. And as you'll see, this also works perfectly fine. You can see this time it was done with a POST request and everything works. The functionality is exactly the same. We don't have any spinner, of course. We don't have any loading indicator because we don't have any JavaScript to trigger that with. But that also shows that when you have JavaScript enabled, feel free to add any extra juicing that you might find suitable. It's just that essential interactions need to work without JavaScript. So what happens here, is that instead of dispatching an action, or telling the server to dispatch an action, we're passing along the name of an action creator. And we have a mapping from action creators to their functions.

4. Making the Counter App Work Without JavaScript

Short description:

And when there's an action creator, the server will await the dispatch of the action creator. Here's a simple counter app that can increment, decrement, and set a custom amount. Disabling JavaScript results in non-functionality because JavaScript is used for all of this. To make it work without JavaScript, remove unnecessary callbacks, import helper components, and change buttons to the button component. The styles disappear when JavaScript is disabled in development mode, but the functionality remains.

And when there's an action creator, the server will notice that and just await the dispatch of the action creator.

And now for some exciting live coding. Okay, so here's a simple counter app. So it can increment, it can decrement. You can also set a custom amount and increment and decrement by that amount. But now if we disable JavaScript, you'll see that nothing works. And that is because we're using JavaScript for all of this.

Let's just change this into dev mode. And you can see we have all these callbacks and onClick handlers. So let's make this work without JavaScript. First of all, let's get rid of everything we don't need, which is all the callbacks. We won't be using any onClick handlers, nor will we be needing the onChange and the value here. Then let's import our helper components. Let's import the button and let's import the form. And let's just comment out this bottom part so we can fix that later.

So first of all, we'll change these normal buttons to... Sorry, I also forgot we have to remove this type button because we want these to actually submit the forms. So let's change these buttons to the button component. And our first one should... So the button component takes in an Action. And our first one should be the decrement Action. And our second one should be the increment Action. Let's see here if this works. So we can decrement, we can increment. Nice. Okay. And if we disable JavaScript... So, first of all, the styles disappear because Next.js doesn't really like having JavaScript disabled in development mode. But our functionality still works, which is the important part. And I'll show you later the styles in a production build.

5. Adding Form and Surprise

Short description:

We added the action to submit and used the button component instead of a normal button. For this part, we changed the wrapper to be the form component. When pressing the first button, it will decrement by the amount entered in the input. Pressing the second button will increment by the entered amount. We also added a surprise by generating a random number between -50 and 50 using the increment by amount action.

It works as you would expect. Okay, so we got that working and it was just a tiny change. This is less code than before. We just added the action that we wanted to submit and used the button component instead of a normal button.

So, for this part, where you can select your own amount, we'll just change this wrapper to be our form component. And then we want to actually use these normal buttons. But we want it to be so that when you press the first button, it will use the value from this input and decrement by that amount. And if you press the second button, we want to use this value again but increment. And we can do that by saying that the button should have name action type and the value of decrement by amount dot type. And what will happen here is that when the form is submitted by pressing this button, only the value of the submitted button will be in the payload itself and client side on the event dot submitter. So we do the same here. We say that name should be action type, which corresponds to the name of the action, should in this case increment by amount dot type. And we also have to say that the payload is this number input. Let's try. OK, sorry. We also have to specify that the payload should be JSON. So now this works correctly. And if we disable JavaScript as well, that also works. Cool.

But I want to add one last thing. I like surprises. So let's add a little surprise as well. Let's give this some styles. And we'll add a button here with the class name of button and surprise. So I want to add a random number between minus 50 and 50. And we can do this by using the action of course, and increment by amount. And pass in, just some quick math here. Get a random number, multiply that with 100, and subtract 50, and if we check this out, this works beautifully. And... If we disable JavaScript, this also works.

6. Working Without JavaScript

Short description:

If we refresh the page, we get the same number because we resend the same state and hardcoded random numbers. Instead of using just an action, we pass the name of an action creator called increment by surprise. This allows us to get a new random number every time, even when JavaScript is disabled. There are some caveats, such as essential interactions not working without JavaScript and the increased server load. However, by leveraging forms and an event-based store, we can create applications that work seamlessly with or without JavaScript.

Great. But the thing is that if you decide to refresh the page, you'll see that we get the exact same number every time. And that's because we're resending the exact same state and we also hardcoded the random numbers. And that is also being resend when we resubmit the form. That's not very surprising, is it?

So instead of using just an action, we'll just pass the name of an action creator. And I made this called increment by surprise. And if we click that, we'll see we still get a random number. And if we disable JavaScript and we refresh, we get a new random number each time. Because now the action creator is being run server side, which regenerates the random number every time. And I wanted to show you this as well. If I actually do a production build here and start the server, you see that the styles actually work without JavaScript as well. So it's just in dev mode.

OK, so there are some caveats with employing this method. And one of them is that you can't have any essential interactions usable only through JS events. So you can't have any, as I said, essential interactions behind things like a hover, or drag and drop, or a long press, and stuff like that. And there's some extra markup that you have to consider when styling because we're adding forms everywhere. There's also lots of refreshing. And I'd say that this isn't really a caveat or an issue. Because oftentimes, for a user without JavaScript enabled, the alternative would be no application or just no updates. And there's an increased server load because we're telling our server to handle more stuff, dispatch actions, and more re-renders that we can't optimize like we can the static GetPages. And when you add GetInitialProps to your Next.js pages, you lose some optimization, which is also sad. I wish there was a way to only enable the GetInitialProps on Post requests, so maybe that'll come someday. Fingers crossed.

And to summarize. By leveraging forms and an event-based store, we can have one application that will seamlessly work whether or not the user has JavaScript enabled in the browser or not. And we can use some helper components to make our lives easier when developing an application like this. But this implementation in itself might not be perfect. I'm well aware of that. What I'm presenting to you is simply a generalized approach or a way of thinking about making applications that work without JavaScript. And if you know of a better way or can think of a better way, or have suggestions and ideas on how to improve this, I'd love to hear them. And please reach out to me. I'm at Portrait2K on Twitter and everywhere. And I'd love to hear what you've done and if you're using this and what do you think about it. So thank you for watching this talk. And big thanks to React Advanced for having me.

Check out more articles and videos

We constantly think of articles and videos that might spark Git people interest / skill us up or help building a stellar career

Node Congress 2022Node Congress 2022
26 min
It's a Jungle Out There: What's Really Going on Inside Your Node_Modules Folder
Top Content
Do you know what’s really going on in your node_modules folder? Software supply chain attacks have exploded over the past 12 months and they’re only accelerating in 2022 and beyond. We’ll dive into examples of recent supply chain attacks and what concrete steps you can take to protect your team from this emerging threat.
You can check the slides for Feross' talk here.
Node Congress 2022Node Congress 2022
34 min
Out of the Box Node.js Diagnostics
In the early years of Node.js, diagnostics and debugging were considerable pain points. Modern versions of Node have improved considerably in these areas. Features like async stack traces, heap snapshots, and CPU profiling no longer require third party modules or modifications to application source code. This talk explores the various diagnostic features that have recently been built into Node.
You can check the slides for Colin's talk here. 
JSNation 2023JSNation 2023
22 min
ESM Loaders: Enhancing Module Loading in Node.js
Native ESM support for Node.js was a chance for the Node.js project to release official support for enhancing the module loading experience, to enable use cases such as on the fly transpilation, module stubbing, support for loading modules from HTTP, and monitoring.
While CommonJS has support for all this, it was never officially supported and was done by hacking into the Node.js runtime code. ESM has fixed all this. We will look at the architecture of ESM loading in Node.js, and discuss the loader API that supports enhancing it. We will also look into advanced features such as loader chaining and off thread execution.
JSNation Live 2021JSNation Live 2021
19 min
Multithreaded Logging with Pino
Top Content
Almost every developer thinks that adding one more log line would not decrease the performance of their server... until logging becomes the biggest bottleneck for their systems! We created one of the fastest JSON loggers for Node.js: pino. One of our key decisions was to remove all "transport" to another process (or infrastructure): it reduced both CPU and memory consumption, removing any bottleneck from logging. However, this created friction and lowered the developer experience of using Pino and in-process transports is the most asked feature our user.In the upcoming version 7, we will solve this problem and increase throughput at the same time: we are introducing pino.transport() to start a worker thread that you can use to transfer your logs safely to other destinations, without sacrificing neither performance nor the developer experience.

Workshops on related topic

Node Congress 2023Node Congress 2023
109 min
Node.js Masterclass
Workshop
Have you ever struggled with designing and structuring your Node.js applications? Building applications that are well organised, testable and extendable is not always easy. It can often turn out to be a lot more complicated than you expect it to be. In this live event Matteo will show you how he builds Node.js applications from scratch. You’ll learn how he approaches application design, and the philosophies that he applies to create modular, maintainable and effective applications.

Level: intermediate
JSNation 2023JSNation 2023
104 min
Build and Deploy a Backend With Fastify & Platformatic
WorkshopFree
Platformatic allows you to rapidly develop GraphQL and REST APIs with minimal effort. The best part is that it also allows you to unleash the full potential of Node.js and Fastify whenever you need to. You can fully customise a Platformatic application by writing your own additional features and plugins. In the workshop, we’ll cover both our Open Source modules and our Cloud offering:- Platformatic OSS (open-source software) — Tools and libraries for rapidly building robust applications with Node.js (https://oss.platformatic.dev/).- Platformatic Cloud (currently in beta) — Our hosting platform that includes features such as preview apps, built-in metrics and integration with your Git flow (https://platformatic.dev/). 
In this workshop you'll learn how to develop APIs with Fastify and deploy them to the Platformatic Cloud.
Node Congress 2023Node Congress 2023
63 min
0 to Auth in an Hour Using NodeJS SDK
WorkshopFree
Passwordless authentication may seem complex, but it is simple to add it to any app using the right tool.
We will enhance a full-stack JS application (Node.JS backend + React frontend) to authenticate users with OAuth (social login) and One Time Passwords (email), including:- User authentication - Managing user interactions, returning session / refresh JWTs- Session management and validation - Storing the session for subsequent client requests, validating / refreshing sessions
At the end of the workshop, we will also touch on another approach to code authentication using frontend Descope Flows (drag-and-drop workflows), while keeping only session validation in the backend. With this, we will also show how easy it is to enable biometrics and other passwordless authentication methods.
Table of contents- A quick intro to core authentication concepts- Coding- Why passwordless matters
Prerequisites- IDE for your choice- Node 18 or higher
JSNation Live 2021JSNation Live 2021
156 min
Building a Hyper Fast Web Server with Deno
WorkshopFree
Deno 1.9 introduced a new web server API that takes advantage of Hyper, a fast and correct HTTP implementation for Rust. Using this API instead of the std/http implementation increases performance and provides support for HTTP2. In this workshop, learn how to create a web server utilizing Hyper under the hood and boost the performance for your web apps.
React Summit 2022React Summit 2022
164 min
GraphQL - From Zero to Hero in 3 hours
Workshop
How to build a fullstack GraphQL application (Postgres + NestJs + React) in the shortest time possible.
All beginnings are hard. Even harder than choosing the technology is often developing a suitable architecture. Especially when it comes to GraphQL.
In this workshop, you will get a variety of best practices that you would normally have to work through over a number of projects - all in just three hours.
If you've always wanted to participate in a hackathon to get something up and running in the shortest amount of time - then take an active part in this workshop, and participate in the thought processes of the trainer.
TestJS Summit 2023TestJS Summit 2023
78 min
Mastering Node.js Test Runner
Workshop
Node.js test runner is modern, fast, and doesn't require additional libraries, but understanding and using it well can be tricky. You will learn how to use Node.js test runner to its full potential. We'll show you how it compares to other tools, how to set it up, and how to run your tests effectively. During the workshop, we'll do exercises to help you get comfortable with filtering, using native assertions, running tests in parallel, using CLI, and more. We'll also talk about working with TypeScript, making custom reports, and code coverage.