How to Cache Ejs and Built the Progressive Web Application with Nodejs?
Last Updated :
16 Jul, 2024
To cache EJS (Embedded JavaScript) templates and build a Progressive Web Application (PWA) with Node.js, we need to leverage several key technologies. Caching EJS templates can significantly enhance performance by reducing the need to recompile templates on each request. we'll learn how to cache EJS and build the Progressive Web Application with Nodejs in details.
Understanding Progressive Web Apps (PWAs)
Before diving into the development process, it's crucial to understand what Progressive Web Apps (PWAs) are. PWAs are web applications that utilize modern web technologies to deliver an experience similar to native apps, regardless of the platform. They offer features such as offline functionality, push notifications, and enhanced performance, making them an excellent choice for boosting user engagement and retention.
Setting Up the Node.js Environment
The first step is to set up the Node.js environment on your computer. Download and install Node.js from the official website. Make sure that the npm (Node Package Manager) is also installed. You can check the installation by running the following commands in your terminal:
node -v
npm -v
Approach
- The first step is to create a new file and name it server.js or index.js and configure a basic Express server:
- First, create a directory named public in the root of your project. This directory will hold the static assets for your PWA, such as, CSS, and JavaScript files.
- Service workers are a core component of PWAs, providing offline functionality and caching capabilities. To implement a service worker, create a new file named service-worker.js in the public directory of our project.
- Within the views directory, create an index.ejs file. This file will serve as the entry point for our PWA.
- To bundle your frontend code and service worker into a single file, you need to set up Webpack. Create a new file named webpack.config.js in the root directory of your project.
Steps to create application
Step 1: Creating a New Node.js Project
- To create a new Node.js project, use npm. Navigate to the directory where you want your project to be located and run the following command:
npm init -y
- This command initializes a new Node.js project with default settings, generating a package.json file that contains your project's metadata and dependencies.
- To set up your project's package.json file, which will manage your project's dependencies, follow these steps.
Step 2: Installing Required Dependencies
To build Progressive Web Apps (PWAs), you'll need several dependencies to manage service workers, caching, and other PWA functionalities. Use npm to install the following packages:
npm install express
npm install workbox-webpack-plugin
Project Structure:
Updated dependencies in package.json :
"dependencies": {
"ejs": "^3.1.9",
"express": "^4.18.3",
"nodemon": "^3.1.0"
}
Example: In this example we'll learn how to build the Progressive Web Application with Nodejs
HTML
<!-- views/index.ejs -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="/style.css">
<title>Home</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
height: 100vh;
background-color: #f4f4f4;
}
h1 {
color: #333;
}
</style>
</head>
<body>
<h1>Welcome to My PWA</h1>
<p> This is my Home page</p>
<script src="/js/main.js"></script>
</body>
</html>
JavaScript
// public/js/main.js
if ('serviceWorker' in navigator) {
window.addEventListener('load', () => {
navigator.serviceWorker.register('/service-worker.js')
.then(registration => {
console.log('ServiceWorker registration successful with scope: ',
registration.scope);
})
.catch(error => {
console.log('ServiceWorker registration failed: ', error);
});
});
}
JavaScript
// public/service-worker.js
const CACHE_NAME = 'my-pwa-cache-v1';
const urlsToCache = [
'/',
'/css/styles.css',
'/js/main.js',
];
self.addEventListener('install', event => {
event.waitUntil(
caches.open(CACHE_NAME)
.then(cache => {
console.log('Opened cache');
return cache.addAll(urlsToCache);
})
);
});
self.addEventListener('fetch', event => {
event.respondWith(
caches.match(event.request)
.then(response => {
if (response) {
return response; // Cache hit - return response
}
return fetch(event.request); // Fetch from network
}
)
);
});
self.addEventListener('activate', event => {
const cacheWhitelist = [CACHE_NAME];
event.waitUntil(
caches.keys().then(cacheNames => {
return Promise.all(
cacheNames.map(cacheName => {
if (!cacheWhitelist.includes(cacheName)) {
return caches.delete(cacheName);
}
})
);
})
);
});
JavaScript
// webpack.config.js
const path = require('path');
const { InjectManifest } = require('workbox-webpack-plugin');
module.exports = {
entry: './views/index.js',
plugins: [
new InjectManifest({
swSrc: './public/service-worker.js',
swDest: 'service-worker.js',
}),
],
};
Node
// server.js
const express = require('express');
const path = require('path');
const app = express();
// Set EJS as the templating engine
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));
// Serve static files
app.use(express.static(path.join(__dirname, 'public')));
// Define routes
app.get('/', (req, res) => {
res.render('index');
});
// Start the server
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});
Step 3: Run the Server
Finally, launch your Node.js server to see your PWA in action by running the following command:
nodemon server.js
Output:
Similar Reads
How to Build a Progressive Web App (PWA) from Scratch? A Progressive Web App (PWA) is a kind of application software sent through the web, formed using standard web technologies such as HTML, CSS, and JavaScript. PWAs are planned to work on any platform that uses a standards-compliant browser, containing both desktop and portable devices. Steps to Build
3 min read
How to Build a Simple Web Server with Node.js ? Node.js is an open-source and cross-platform runtime environment for executing JavaScript code outside a browser. You need to remember that NodeJS is not a framework, and itâs not a programming language. Node.js is mostly used in server-side programming. In this article, we will discuss how to make
3 min read
How to Combine Multiple Node.js Web Applications ? As web applications become increasingly complex, it's not uncommon for organizations to have multiple Node.js applications serving different purposes. However, managing and integrating these applications can present challenges. In this article, we will explore various approaches and best practices f
3 min read
How to Deploy Node.js Express Application on Render ? Deploying a Node.js Express application on Render is straightforward and involves a few key steps to set up your project, configure deployment settings, and manage your application on the Render platform. Render provides an easy-to-use platform for deploying applications, offering features like auto
4 min read
Steps to Create an Express.js Application Creating an Express.js application involves several steps that guide you through setting up a basic server to handle complex routes and middleware. Express.js is a minimal and flexible Node.js web application framework that provides a robust set of features for web and mobile applications. Hereâs a
10 min read
Build a Node.js-powered Chatroom Web App In this article, we are going to create a chatroom web app using Node.js. A Chatroom Web App is basically used to create a chatroom that is similar to a group chat, where users can come and join the group/ chatroom, send messages to the chatroom, and see other users' messages.We are going to set up
5 min read