10th November, 2024•📖 3 min read

Escaping SSL Errors in Next.js: A Clever Workaround for Smooth Client-Side Data Fetching

Israel MichaelIsrael Michael
Escaping SSL Errors in Next.js: A Clever Workaround for Smooth Client-Side Data Fetching

Introduction

Building a data-driven application in Next.js is generally smooth, but things got tricky when I faced an SSL certificate error. The journey turned into a deep dive into client-server interactions, SSL certificates, and a workaround involving custom API routes. If you’re working with data fetching in Next.js and need to dodge SSL verification errors, this post is for you.

Starting Out: A Simple Server Component

The project began with a server component meant to fetch data directly from an external API and display it on the page. The logic was simple: call the API and render the data immediately on the server side. Here’s the initial setup:

// Server component example
import axios from "axios";

export default async function Page() {
  const response = await axios.get("https://your-external-api.com/data");
  const globalData = response.data;

  return <div>{/* Render globalData here */}</div>;
}

It seemed straightforward, but as soon as I deployed the component and ran it in production, I hit a wall. I was greeted by a net::ERR_CERT_AUTHORITY_INVALID error, indicating that the SSL certificate wasn’t fully trusted. This halted the entire process and left the page unable to fetch or display any data.

SSL Errors Explained: Why This Happens

SSL errors like ERR_CERT_AUTHORITY_INVALID usually mean that the server’s SSL certificate can’t be verified as trustworthy. In my case, the API’s SSL certificate didn’t meet the standard trusted certificate authorities in the browser. This is a common issue when working with certain staging APIs or self-signed certificates.

The Workaround: Creating an API Route in Next.js

To avoid this SSL error, I decided to set up an API route in Next.js. This approach allowed me to make the initial API call from the Next.js server, bypassing the SSL error by ignoring the certificate verification only server-side. Here’s how I set it up:

1. Create a new API route:

  • This API route serves as a proxy between my Next.js app and the external API, handling the data fetching server-side.
// /pages/api/fetchGlobalData.js
import axios from "axios";
import https from "https";

export default async function handler(req, res) {
  try {
    const httpsAgent = new https.Agent({
      rejectUnauthorized: false, // Ignore SSL verification
    });
    const response = await axios.get("https://your-external-api.com/data", {
      httpsAgent,
    });
    res.status(200).json(response.data);
  } catch (error) {
    console.error("Error fetching data:", error);
    res.status(500).json({ error: "Failed to fetch data" });
  }
}

In this setup:

  • The httpsAgent instance is configured with rejectUnauthorized: false, which skips SSL verification, avoiding the error.
  • The Next.js API route /api/fetchGlobalData acts as a go-between, making the request to the external API and returning the data to my frontend.

2. Fetch Data in the Client Component:

  • With the API route ready, I updated my client component to fetch data from this new endpoint.
"use client";

import { useEffect, useState } from "react";

export default function Page() {
  const [globalData, setGlobalData] = useState(null);
  const [error, setError] = useState(false);

  const fetchData = async () => {
    try {
      const response = await fetch("/api/fetchGlobalData");
      if (!response.ok) throw new Error("Network response was not ok");
      const data = await response.json();
      setGlobalData(data);
      setError(false);
    } catch (err) {
      console.error("Failed to fetch data:", err);
      setError(true);
    }
  };

  useEffect(() => {
    fetchData();
    const interval = setInterval(fetchData, 120000); // Fetch every 2 minutes
    return () => clearInterval(interval);
  }, []);

  if (error) return <div>Error loading data</div>;
  if (!globalData) return <div>Loading...</div>;

  return <div>{/* Render globalData here */}</div>;
}

The Benefits of This Approach

  • SSL Error Bypassed: By fetching data on the server side, the browser is shielded from any SSL certificate issues.
  • Secure Data Handling: Sensitive data remains secure, as it’s handled entirely on the server.
  • Consistent Refetching: With setInterval, I could refetch every 2 minutes, ensuring the data stays up-to-date without worrying about SSL issues impacting the client.

Wrapping Up

Converting my server component to an API route was a game-changer for this project. By letting the server handle SSL verification, I kept the client-side data flow smooth and reliable. The final implementation of this clever workaround allowed me to bypass SSL errors entirely while providing an effective and synchronized data-fetching setup.

So, if you’re working in Next.js and encounter SSL issues, consider this approach, it’s a straightforward solution to a frustrating problem.