Client-Side Caching
For elements that don’t change often, like images and CSS, Alex uses service workers to cache them on the user’s browser. She creates a service worker that caches assets upon the first visit so that subsequent visits require no additional network requests for those assets.
Practical Implementation: This would involve creating a service worker file and registering it in the Next.js application. However, Next.js doesn’t natively support service workers out of the box, so Alex uses next-pwa
, a plugin that makes it easier.
Step 1: Install next-pwa
Install next-pwa
and webpack
(if it’s not already installed) in your Next.js project:
npm install next-pwa webpack
JavaScriptStep 2: Configure next-pwa
in next.config.js
Create or edit your next.config.js
file to include next-pwa
configuration:
// next.config.js
const withPWA = require('next-pwa');
const runtimeCaching = require('next-pwa/cache');
module.exports = withPWA({
pwa: {
dest: 'public',
runtimeCaching,
},
// other next.js config here
});
JavaScriptStep 3: Add the Service Worker
next-pwa
will automatically generate a service worker for you. However, you need to ensure that your public
directory has the following files which next-pwa
looks for:
public/manifest.json
- Icons in
public
directory referenced bymanifest.json
Example manifest.json
:
// public/manifest.json
{
"short_name": "NextPWA",
"name": "Next.js PWA Example",
"icons": [
{
"src": "/icons/android-chrome-192x192.png",
"type": "image/png",
"sizes": "192x192"
},
{
"src": "/icons/android-chrome-512x512.png",
"type": "image/png",
"sizes": "512x512"
}
],
"start_url": "/",
"display": "standalone",
"theme_color": "#FFFFFF",
"background_color": "#FFFFFF"
}
JavaScriptStep 4: Register the Service Worker
In your pages/_app.js
file, register the service worker using next-pwa
‘s register
method. This is often done in a useEffect
to ensure it registers after the application has mounted:
// pages/_app.js
import { useEffect } from 'react';
import { register } from 'next-pwa';
export default function MyApp({ Component, pageProps }) {
useEffect(() => {
register();
}, []);
return <Component {...pageProps} />;
}
JavaScriptStep 5: Test Your PWA
- Build your Next.js application to ensure the service worker is generated:
npm run build
npm start
Bash- Use Lighthouse in Chrome DevTools to test if your application meets PWA criteria.
Step 6: Deploy Your PWA
- Deploy your application on a server or platform that supports HTTPS because service workers require a secure context.
By following these steps, you’ve turned your Next.js application into a PWA with offline capabilities and more. This can enhance user experience, especially for return visits, by caching assets and enabling your web app to load quickly and function offline or on flaky network connections.