Building an Offline-First Application With Node.js and SQLite | by Arctype | Apr, 2022

Building an offline-first application with Node.js and SQLite

“Offline first” is an software growth paradigm during which builders be sure that an app’s performance is unaffected by a brief lack of community connectivity. Progressive internet functions, which really feel like native functions however run like internet functions, are sometimes constructed on this paradigm.

This tutorial will train you how one can construct an offline-first software with Node.js and an SQLite database. Let’s begin with an introduction to progressive internet apps.

Progressive web apps (PWAs) are internet apps that use service staff, manifests, and different web-platform options and progressive enhancement to supply customers with an expertise akin to native apps.

PWAs can generally outperform native apps when it comes to effectivity. They function on demand and are at all times obtainable with out consuming helpful smartphone reminiscence or knowledge. Customers devour much less knowledge when selecting a PWA over a local model of the identical software. They will nonetheless save the PWA to their dwelling display; it’s installable with out the necessity for a full obtain.

To reveal the facility of progressive internet functions, we’ll be constructing a easy weblog software.

Building an offline-first application with Node.js and SQLite

The consumer will be capable of work together with it like different PWAs, such because the Twitter PWA. Let’s get proper to it.

Let’s get our palms soiled. To get began, we’ll create our mission folder with the command beneath:

mkdir PWA && cd PWA

Then, we’ll initialize a Node.js software with the instructions beneath:

npm init -y

The above command creates a package deal.json file for the applying.

Subsequent, create the next folder construction in our mission folder:

📦PWA
┣ 📂public
┃ ┣ 📂 css
┃ ┣ 📂icons
┃ ┣ 📂pictures
┃ ┣ 📂js
┃ ┗ 📜index.html
┗ 📜package deal.json

With our software setup, let’s set up Categorical to create our Node.js server with the command beneath:

npm set up categorical

Then, we’ll create a few folders and information within the public folder:

  • css/type.css file
  • js/app.js file

Subsequent, create an index.js file within the mission root listing with the next code snippets beneath:

Within the code snippet, we import categorical to create our server and the path module. We configured our app to render our static information utilizing the categorical.static methodology, which takes the trail to the static folder (public), after which we created the basis route of our software and rendered the index.html file. Then we configured the app to hearken to port 8000.

With the server arrange for our software, let’s create and join our software to save lots of our weblog particulars. To get began, run the command beneath to put in the sqlite3 dependency:

npm set up sqlite3

Then, on the entry level of the index.js file, add the code snippet beneath to create and join the applying to an SQLite Database.

Subsequent, we’ll create a listing of blogs that we’ll retailer in our database and render later to the client-side with the code snippet beneath:

Every block submit in our software could have an id, title, avatar, and intro discipline.

Now, create a database desk named blogs and save the weblog particulars we simply created above with the code snippet beneath:

Within the code snippet, we created a desk blogs utilizing db.run. The db.run methodology takes an SQL question as a parameter, then we loop by our array of blogs and insert them into the blogs desk we simply created utilizing the js map operate.

Now, let’s view the information we simply created utilizing Arctype. To view the information in your SQLite database utilizing Arctype, observe the steps beneath:

  • Set up Arctype
  • Run the applying with node index.js to create a database
  • Launch Arctype, and click on on the SQLite tab
Building an offline-first application with Node.js and SQLite
  • Click on on the Choose SQLite file button, and find the db.sqlite file generated once you ran the server.
  • It’s best to see the blogs desk and the information we create as proven within the screenshot beneath:
Building an offline-first application with Node.js and SQLite

At this level, we’ve linked the applying to an SQLite database and likewise inserted some information within the database. Now, open the index.html file and add the next code snippets beneath:

We created a easy markup with hyperlinks to our manifest within the above file, which we’ll be creating within the subsequent part, kinds, and app.js information.

Then, we’ll create a blogs route in our index.js file to return the blogs to the client-side.

...
app.get("/blogs", (req, res) =>
res.standing(200).json(
blogs,
);
);
...

In our public/js/app.js file, we’ll ship a get request to the weblog endpoint to get the blogs from our backend. Then we loop by the blogs, goal the container class and show them with the next code:

We’ll additionally add some styling to our software within the public/css/type.css with the code snippet beneath:

Now open the package deal.json file and add the beginning script.

"begin": "node index.js"

At this level, we’ve arrange our software. However we can’t run our software when the server just isn’t working or when there isn’t a community connection for manufacturing. Let’s set that up within the subsequent part.

We have to make our software suitable with all display sizes. We’ll additionally add a theme shade by including the markup beneath within the head part of our index.html file.

<meta identify="viewport" content material="width=device-width, initial-scale=1">
<meta identify="theme-color" content material="#16a0d6e7"/>

We have to describe our app and the way it ought to behave when put in on the consumer’s system. We will do that by making a manifest.

Create a manifest file within the mission root listing and add the next configurations:


"identify": "Blogger"
"short_name": "Blogger"
"start_url": "/",
"show": "standalone",
"background_color": "#0e9c95",
"theme_color": "#16a0d6e7",
"orientation": "portrait",
"icons": []

In our manifest, we outlined the next configurations:

  • identify: This defines the app’s show identify.
  • short_name: This defines the identify that might be displayed beneath the app icon when put in.
  • start_url: This tells the browser the basis URL of the applying.
  • show: This tells the browser how one can show the app.
  • background_color: This defines the background shade of the applying when put in.
  • theme_color: This defines the colour of the standing bar.
  • orientation: This defines the orientation to make use of through the app show.
  • icons: This defines the icons or pictures of various sizes for use as our app dwelling icons.

Creating our dwelling display icons manually is usually a very sophisticated job, however to not fear. We’ll benefit from a third-party module often called pwa-asset-generator to generate icons of various sizes from our principal app icon inside the general public listing with the command beneath:

#change listing to the general public folder
cd public
#generate icons
npx pwa-asset-generator brand.png icons

The above command will create an icons folder inside the general public folder with many icons for our software, together with some JSON on the terminal that we are going to paste into our icons array within the manifest.

Building an offline-first application with Node.js and SQLite

The icons array in our manifest ought to appear like this:

Additionally, the command generated the markup hyperlinks to the icons generated.

Building an offline-first application with Node.js and SQLite

Copy and paste the markup to the top part of the markup within the public/index.html file.

With our manifest created, let’s arrange the service staff. A service employee is a chunk of JavaScript code that your browser runs within the background in a separate thread to deal with the cache for property and knowledge that you just save for future requests to allow offline assist to your software.

So, create a blogger.serviceWorker.js file within the public folder. For the service employee, there are lots of occasions (push, activate, set up, fetch, message, sync), however for the demonstration on this tutorial, we’ll cowl the set up, activate, and fetch occasions. Earlier than that, we have to create an array to retailer all of the property we utilized in our software.

const property = [
"/",
"css/style.css",
"js/app.js",
"/images/blog1.jpg",
"/images/blog2.jpg",
"/images/blog3.jpg,"
];

Then, we’ll hearken to the set up occasion to register and save our static information to the browser’s cache. This course of takes a while to finish. To skip the wait, we’ll use skipWaiting().

Then, we have to clear the cache to take away the outdated property at any time when the service employee is up to date. For that, we’ll hearken to the activate code snippet beneath:

Within the above code snippet, we use the waitUntil methodology on the service employee. This methodology waits for the motion to complete, after which we verify if the property we try to clear are the property of our present app earlier than we delete them.

Subsequent, we’d like the information saved in our cache to make use of them.

When a request is made on the web page, PWA will verify our cache and browse from it if there may be knowledge within the cache reasonably than going to the community. Then, utilizing the respondWith methodology, we override the browser’s default and make our occasion return a promise. When the cache is full, we are able to return the cache equivalent to the evt.request. When the cache is prepared, we are able to return the cache that matches the evt.request.

We have now efficiently arrange our service employee. Now let’s make it obtainable in our software.

Now, let’s register our service employee in our public/js/app.js file with the code snippet beneath:

Right here, we verify if our software’s browser helps service staff (in fact, not all browsers assist service staff), then register our service employee file.

Now, run the applying with the command beneath:

npm begin

Go to localhost:8000 in your browser to entry the app.

Now, let’s verify if we correctly arrange our PWA utilizing a Google Lighthouse verify. Proper-click in your browser and choose “examine.” On the examine tabs, choose lighthouse and click on on generate report. If the whole lot went nicely along with your software, you must see an output just like the one within the screenshot beneath:

Building an offline-first application with Node.js and SQLite

We have now efficiently created our first software. You can even cease the server to check the applying in offline mode.

Progressive internet apps (PWA) use trendy APIs to supply enhanced capabilities, dependability, and installability with a single codebase. They permit your finish consumer to make use of your software no matter whether or not or not they’ve an web connection.

It’s best to be happy to fork the repository and add extra options to the mission.

Good luck!

More Posts