Ensuring a great user experience often involves handling network disruptions gracefully. In this article, we’ll learn how to detect network connection changes in a Next.js application and display a warning to users when the connection is lost.
navigator is provided by modern browsers. onLine property and online/offlineevents to keep track of network changes.
navigator.onLine: It returns true if the browser is in online state. online and offline events: It fired when the network status is changed.
In this article we’ll create a NetworkStatus component, that:
Step 1: Create a NetworkStatus Component
Create a new file components/NetworkStatus.jsx.
Step 2: Add the Created Component into Your App
Add the NetworkStatus component to your layout or pages/_app so the warning is accessible globally. js.
Then Modify pages/_app.js:
Step 3: Style the Warning Banner
Add custom styling to make the banner fit your application’s design. For example, you can extend the bannerStyles in the NetworkStatus component or define styles in your global CSS file (styles/globals.css).
Update the component to use the created css class:
Step 4: Handle Advanced Scenarios (Optional)
Custom Alerts or Modals: Instead of a banner, you could use a modal to block user actions when offline.
Polling for Connection: If navigator.onLine is unreliable, consider polling a server endpoint periodically to check connectivity.
Example:
Use setInterval to call pingServer every few seconds.
5. Testing the Feature
Simulate Offline Mode: In your browser Chrome DevTools, go to the Network tab, and then select Offline mode from the throttling options.
Reconnect: Return to Online mode in DevTools and observe the banner disappearing.
Final Code Summary
components/NetworkStatus.jsx:
pages/_app.js:
Monitoring network status and informing users about connectivity changes is a small but impactful feature that can significantly enhance the user experience of your Next.js application. With just a few lines of code, you can create a responsive and resilient UI that gracefully handles network disruptions.