In this article, I will show you how to quickly make your NextJS app installable with Chrome.
The goal is to provide the minimum code and assets necessary to activate this feature.
Let’s jump to the implementation and create our NextJS app:
npx create-next-app@latest
Select the options you want, I will answer "Yes" to everything except the last one:
✔ What is your project named? … nextjs-installable
✔ Would you like to use TypeScript? … No / Yes
✔ Would you like to use ESLint? … No / Yes
✔ Would you like to use Tailwind CSS? … No / Yes
✔ Would you like to use `src/` directory? … No / Yes
✔ Would you like to use App Router? (recommended) … No / Yes
✔ Would you like to customize the default import alias? … No / Yes
Let’s test our app with:
cd nextjs-installable
npm run dev
Let's check with Chrome what the Lighthouse PWA report is saying about our app:
First, I will remove the line 31 and 40 from the src/app/page.tsx
file as they are triggering the Content does not size correctly to viewport
in the Lighthouse report and we don't need it for the topic of this article.
Now let's add all the missing features our report is complaining about.
Download any 512x512 PNG image, for example:
https://www.pngmart.com/fr/image/39454
Rename it and put it the following folder:
public/images/icon-512x512.png
Now create a public/manifest.json
file with the following content, feel free to adapt it to your needs:
{
"name": "NextJS Installable",
"short_name": "Installable",
"theme_color": "#000000",
"background_color": "#000000",
"display": "standalone",
"scope": "/",
"start_url": "/",
"description": "Minimal configuration for a NextJS installable app",
"icons": [
{
"src": "/icon-512x512.png",
"sizes": "512x512",
"type": "image/png"
}
]
}
Open the src/app/layout.tsx
and add a link to the manifest.json
file along with the theme color of our app:
export const metadata: Metadata = {
title: 'Create Next App',
description: 'Generated by create next app',
manifest: '/manifest.json',
themeColor: '#000000',
}
Now create the service worker file called public/sw.js
with one single line:
self.addEventListener('fetch', () => {});
and create another file to register our service worker called public/register.sw
with the following content:
if ("serviceWorker" in navigator) {
// declaring scope manually
navigator.serviceWorker.register("/sw.js", { scope: "./" }).then(
(registration) => {
console.log("Service worker registration succeeded:", registration);
},
(error) => {
console.error(`Service worker registration failed: ${error}`);
},
);
} else {
console.error("Service workers are not supported.");
}
Finally let's link our register-sw.js
file in our src/app/layout.tsx
:
<html lang="en">
<Script src='/register-sw.js' />
<body className={inter.className}>{children}</body>
</html>
Let's re-run a Lighthouse report:
And finally, let's open our app with Chrome on our phone. Before that we will deploy it with https://vercel.com:
Top comments (2)
Perfectly explained. Thanks!
Good Job