Our offices

  • Gujarat
    35 Laxminarayan
    382305, Dahegam, Gandhinagar

Follow us

Client-Side Error Handling with Slack Notifications

by Jhanvi Solanki, Software Engineering Trainee

When dynamically generating 1000+ pages, there's always a chance of a page breaking due to incorrect data. Recently, one of our clients experienced this issue with some of their online course pages, due to incorrect data entry in Ghost CMS. To address this, we created a system that sends a Slack message if a user visits a broken page.

1. Create a Slack App

First, create an app on Slack by going to Slack API.

2. Activate Incoming Webhooks

Enable the Incoming Webhooks feature for your app.

3. Add Webhook URLs for Your Workspace

After activating Incoming Webhooks, you will get your webhook URL. Save this URL as you'll need it later.

4. Create an API in the Next.js API Folder

Create a file in the pages/api folder (e.g., errorBoundary.js) and add the following code:

import axios from "axios";

export default async function handler(req, res) {

  try {
    if (req.method === "POST") {
      await axios.post(process.env.NEXT_PUBLIC_SLACK_WEBHOOK_URL, {
        blocks: [
          "YOUR SLACK MESSAGE UI"
      });
      res.status(200).json({ message: "Success" });
    } else {
      res.status(400).json({ message: "Request method not allowed" });
    }
  } catch (err) {
    res.status(500).json({ message: "Something went wrong" });
    console.log(err);
  }
}

5. Setup API Calling Function

Add a function to call the API from your client-side code:

export const sendSlackNotification = async (url, error, type = "Broken Page") => {
  const body = { url, error: error || "", type };
  const response = await fetch("/api/errorBoundary", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(body),
  });
  const data = await response.json();
  console.log(data);
};

6. Create an ErrorBoundary Component

Create an ErrorBoundary component to catch errors and send notifications:

import React from "react";
import { sendSlackNotification } from "@lib/errorHandling";

class ErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = { hasError: false };
  }

  static getDerivedStateFromError(error) {
    return { hasError: true };
  }

  componentDidCatch(error, errorInfo) {
    // Log error to Slack
    sendSlackNotification(window.location.href, error.message);
  }

  render() {
    if (this.state.hasError) {
      return <h1>Something went wrong.</h1>;
    }
    return this.props.children;
  }
}

export default ErrorBoundary;

7. Wrap the Component

Wrap your ErrorBoundary component to _app.jsx file:

<ErrorBoundary>
  <Component {...pageProps} />
</ErrorBoundary>

Conclusion

By integrating Slack notifications with client-side error handling in Next.js, you can proactively monitor and address page breakages, ensuring a seamless experience for your users. This approach provides a robust solution for dynamic page generation issues and keeps your team informed in real-time.

More articles

Integrating the Latest Version of Algolia InstantSearch with Google Maps

Integrating Algolia's InstantSearch with Google Maps can provide powerful search functionality combined with geographical visualization.

Read more

How to Use Shopify’s Storefront API for Headless Commerce

Explore the benefits of headless commerce with Shopify's Storefront API, enabling custom shopping experiences by decoupling the frontend from the backend.

Read more

Tell us about your project

Our offices

  • Gujarat
    35 Laxminarayan
    382305, Dahegam, Gandhinagar