Content Source:
Creating a Progressive Web Application using Next JS
In this article, you will learn about the progressive web app, and why PWA is gaining popularity, and also you can create a simple PWA app using NextJs.
Overview
- Progressive Web App
- Project setup with NextJs
- PWA implementation
Progressive Web App ( PWA )
PWA = web + experience of a native application
What is PWA?
The progressive web app is a simple web application that runs on a web browser similar to that of a website and provides an installable feature on a mobile device. PWA gives you a rich mobile experience via native-like functionalities such as the ability to work offline, push notifications, device hardware accessibility, and many more. Web applications can reach anyone, anywhere, on any device with a single codebase as a result PWA is more special. PWA offers the same experience as the native app and you need not download it from an app store or play store. PWA loads runs and functions in a web browser.
The Native app is known for rich and reliable with its own standalone user experience, the web app are best for reachability. Progressive Web Apps combine the best features of both native and web apps, including native-like functionality, dependability across all platforms with a single codebase, installability, and accessibility to anyone, anywhere. They are designed, developed, and enhanced using cutting-edge and modern APIs.
Why PWA?
Some people may wonder why we need PWA if we can have a separate version of apps like android, IOS, and web. The PWA is gaining popularity because of the following features:
- Installable: Installable on a mobile device and available via the device’s home screen. A PWA feels like a native app on the device with an immersive user experience.
- Offline support: PWA offers the same services as on the web. If you try to load a website without internet connectivity, you will get a message saying you are offline. On the other hand, Progressive Web page enables you to connect to the website, even when you are offline that being said you must visit the PWA at least once before, in an online mode.
- Platform independence: As you know native mobile apps are platform-specific, and can only be accessed from their respective OS like Android or iOS whereas PWA’s are platform independent and can run independently of any OS since they are browser-based.
- Background synchronization: In the mobile application, you have to frequently re-install or update the apps when the new or additional features in the app are integrated. But in the case of PWA, the content is updated in the progressive web apps in the background, and new features are automatically integrated within the website, with a simple page refresh.
- Cost-effective: PWA is quicker to develop with a lesser developmental cost making it cost-effective.
- Enhance Loading Speed: As compared to normal websites, PWA has an instant loading time. As it is based on the method of intelligent caching, the first load, as well as the subsequent loads, are faster. Due to this, the bounce rate for PWA is lower compared to mobile websites.
Project Setup with NextJs
You will use NEXTJS to implement the PWA which is a react framework for developing feature-rich frontend web applications. Now, Let’s create the project executing any commands mentioned below in your terminal based on the package management tool that you have.
npx create-next-app@latest --ts # or yarn create next-app --typescript # or pnpm create next-app --ts
After executing the command you will have a pre-configured NextJs project.
PWA Implementation
Now you will work on the implementation of PWA in the project that you just configured. For PWA implementation you will make use of next-pwa which is a zero-config PWA Plugin for NextJs. Let’s install the plugin in the project using the command below:
yarn add next-pwa npm install next-pwa
Step 1: withPWA
Now, update or create next.config.js
/** @type {import('next').NextConfig} */ const runtimeCaching = require("next-pwa/cache"); const withPWA = require("next-pwa")({ disable: process.env.NODE_ENV === "development", dest: "public", register: true, skipWaiting: false, runtimeCaching, }); const nextConfig = withPWA({}); module.exports = nextConfig;
After running next build, this will generate two files in your public: workbox-*.js and sw.js, which will automatically be served statically.
Step 2: Create a custom server ( optional )
This step is optional. So if you want to use a custom server then you can proceed with this step. To create a custom server using express the root of the project with the file name server.js in order to load the service work. For creating the express server, you need to add express into the project
yarn add express npm install express
const express = require("express"); const next = require("next"); const port = parseInt(process.env.PORT, 10) || 3000; const dev = process.env.NODE_ENV !== "production"; const app = next({ dev, }); const handle = app.getRequestHandler(); app.prepare().then(() => { const server = express(); server.get("/service-worker.js", (req, res) => { app.serveStatic(req, res, "./.next/service-worker.js"); }); server.get("*", (req, res) => { return handle(req, res); }); server.listen(port, (err) => { if (err) throw err; }); });
Step 3: Creating and adding Manifest File
You have to generate the manifest file inside the public folder in the project. For this, you can use any online tool for generating the manifest file.
Fill in all the information and generate the manifest file. After that copy the content into the public directory and rename the file as manifest.json
So now lets _document.tsx page and include the manifest.json link inside the Head tag as below:
import Document, { Html, Head, Main, NextScript } from "next/document"; class MyDocument extends Document { render() { return ( <Html> <Head> <link rel="manifest" href="/manifest.json" /> <link rel="apple-touch-icon" href="/logo.png"></link> <meta name="theme-color" content="#fff" /> </Head> <body> <Main /> <NextScript /> </body> </Html> ); } } export default MyDocument;
You have successfully configured your project with PWA up to this point. Now run the following command and build the project.
yarn build npm build
After build completion starts the build app using the following command:
yarn start npm start
When the app is started, you can see an install icon at the top of the browser like in the above image. Now you can install and use the app.
For more information and to develop web application using React JS, Hire React Developer from us as we give you a high-quality product by utilizing all the latest tools and advanced technology. E-mail us any clock at – hello@hkinfosoft.com or Skype us: “hkinfosoft”.
To develop custom web apps using React JS, please visit our technology page.
Content Source:
- medium.com
Building Progressive Web App using Laravel
Progressive Web App or PWA are the important thing in web development at the moment. Why wouldn't it be? The promise of a website behaving like a native app, without all the hassles.
PWA allow you to install your website on the user’s home screen, work without an internet connection and even send push notifications to users. You can also cache everything to your heart’s content, including API calls with IndexedDB. I’ll run you through the simple setup I used to get things going rather quickly with Laravel 5.8.
To view service worker information in browser when testing, open up devtools and hit the application tab in Chrome.
What do I need for a PWA?
To make sure your website behaves like a PWA, please read the checklist. Here’s the quick and easy summary:
- HTTPS
- manifest.json
- Service Worker
- Responsive Design
Setting things up
Firstly you’re going to want to run npm install –save-dev sw-precache-webpack-plugin. This package uses sw-precache to generate our service worker. If you’re worried about losing control, don’t worry – you can use the importScripts option to include any custom logic that you need.
Service Workers provide us with the black magic that we want. You can read more about them here.
To store information from API calls, I used localforage. It’s a nice little library to interact with IndexedDB or WebSQL. So once you’ve got sw-precache-webpack-plugin installed, it’s time to customize our Laravel project.
Step 1: Update Laravel Mix
You’re going to have to copy webpack’s config file and place it at the root of your project directory. You should be able to find it at:
node_modules/laravel-mix/setup/webpack.config.js.
Once that’s done, you’ll need to update your package.json file to reference the new location. Otherwise our changes won’t affect anything. It’s up to you to decide which build step to include it in. You’ll see the development, watch and production scripts currently have the location set to:
--config=node_modules/laravel-mix/setup/webpack.config.js.
Change that to look like this:
--config=webpack.config.js.
Diving into webpack.config.js
At the top of the file you’ll find all the packages that are being imported. Add the sw-precache plugin here. It should look something like this now:
let path = require('path'); let glob = require('glob'); let webpack = require('webpack'); let Mix = require('laravel-mix').config; let webpackPlugins = require('laravel-mix').plugins; let dotenv = require('dotenv'); let SWPrecacheWebpackPlugin = require('sw-precache-webpack-plugin'); //Our magic
Then above this line module.exports.plugins = plugins;, I’ve added the plugin:
plugins.push( new SWPrecacheWebpackPlugin({ cacheId: 'pwa', filename: 'service-worker.js', staticFileGlobs: ['public/**/*.{css,eot,svg,ttf,woff,woff2,js,html}'], minify: true, stripPrefix: 'public/', handleFetch: true, dynamicUrlToDependencies: { '/': ['resources/views/welcome.blade.php'], '/articles': ['resources/views/articles.blade.php'] }, staticFileGlobsIgnorePatterns: [/\.map$/, /mix-manifest\.json$/, /manifest\.json$/, /service-worker\.js$/], runtimeCaching: [ { urlPattern: /^https:\/\/fonts\.googleapis\.com\//, handler: 'cacheFirst' }, { urlPattern: /^https:\/\/www\.thecocktaildb\.com\/images\/media\/drink\/(\w+)\.jpg/, handler: 'cacheFirst' } ], importScripts: ['./js/push_message.js'] }) );
The sw-precache package is pretty well documented, so I won’t go into too much depth. I will give a quick rundown of some of the options seen above.
- staticFileGlobs: The files that we want cached.
- dynamicUrlToDependencies: Map the routes to the absolute path of our files. Don’t forget this
- runtimeCaching: Allows us to save 3rd party libraries in cache.
- importScripts: This includes our custom logic to the generated service worker.
That’s it! When compiling your assets, the service-worker.js should show up in your public folder.
Step 2: The manifest file
The manifest file also sits in your public folder as manifest.json. This file gives you a bit more control on the behaviour of your app. You can read more about it here. But as a quick overview, here’s an example:
{ "short_name": "Shots", "name": "Shots App", "background_color": "#2196F3", "orientation": "portrait", "icons": [ { "src": "icons/icon-36.png", "sizes": "36x36", "type": "image/png" }, { "src": "icons/icon-48.png", "sizes": "48x48", "type": "image/png" }, { "src": "icons/icon-72.png", "sizes": "72x72", "type": "image/png" }, { "src": "icons/icon-96.png", "sizes": "96x96", "type": "image/png" }, { "src": "icons/icon-144.png", "sizes": "144x144", "type": "image/png" }, { "src": "icons/icon-168.png", "sizes": "168x168", "type": "image/png" }, { "src": "icons/icon-192.png", "sizes": "192x192", "type": "image/png" }, { "src": "icons/icon-256.png", "sizes": "256x256", "type": "image/png" } ], "start_url": "/?launcher=true", "display": "standalone" }
- short_name: The name shown on the homescreen of the mobile device.
- name: The name shown on the install banner/popup.
- background_color: The color that is shown just before you app launches.
- orientation: Enforces the orientation to be used.
- start_url: The default page to load when our app launches.
- display: ‘standalone’ or ‘browser’, where browser adds an address bar.
- icons: These are the images for our apps icon on the homescreen. Catering for most screen sizes.
These are just a few of the options that are available to you.
Step 3: Check for PWA support
In the page that you define your layout, include the following:
if ('serviceWorker' in navigator &amp;&amp; 'PushManager' in window) { window.addEventListener('load', function() { navigator.serviceWorker.register('/service-worker.js').then(function(registration) { // Registration was successful console.log('ServiceWorker registration successful with scope: ', registration.scope); }, function(err) { // registration failed. console.log('ServiceWorker registration failed: ', err); }); }); }
This snippet will check for service worker and push notification support and if true, it will load our service worker file.
Done
This is basically all you need to get the PWA behavior. The rest is up to you to customize and configure based on requirements.
The documentation will provide you with all the finer details that you’ll need.
Demo Web App Developed with PWA
Pet Trainer
Pet trainer app developed in Laravel and integrated PWA.
Technology: Laravel 5.8, Service Worker, Manifest.
Conclusion
This is the quickest way to get started and seeing PWA behavior in action with Laravel. I didn’t want to go through the finer details as it’ll be cumbersome writing about all the possible issues you might encounter. If you do find yourself stuck on something, refer to the documentation, it really is your best friend. 🙂
Good luck!
For more Information and to build a website using Laravel, Hire Laravel Developer from us as we give you a high-quality product by utilizing all the latest tools and advanced technology. E-mail us any clock at – hello@hkinfosoft.com or Skype us: “hkinfosoft“.
To develop the custom website using Laravel, please visit our technology page
- medium.com