Next.js Discord

Discord Forum

Best way for next to check for 401 and redirect?

Unanswered
Basset Artésien Normand posted this in #help-forum
Open in Discord
Basset Artésien NormandOP
This is when using a separate server / backend hosted elsewhere.

4 Replies

Toyger
not exactly in nextjs, but for react I used axios and it interceptors for such thing
Basset Artésien NormandOP
i saw that somewhere else. I was trying to avoid using Axios as its a huge package.
@Basset Artésien Normand i saw that somewhere else. I was trying to avoid using Axios as its a huge package.
Toyger
other way probably create some kind of hook wrapper for fetch , to have some kind of custom interceptors, here is quick example from chatgpt
import { useEffect } from 'react';
import { useRouter } from 'next/router';

function useCustomFetch(url, options, onDataReceived) {
  const router = useRouter();

  useEffect(() => {
    const fetchData = async () => {
      try {
        const response = await fetch(url, options);

        if (response.status === 401) {
          // Redirect to the main page or login page
          router.push('/');
        } else {
          // Continue processing the response
          const data = await response.json();
          console.log('Received data:', data);

          // Run the provided callback on the received data
          if (typeof onDataReceived === 'function') {
            onDataReceived(data);
          }

          // Add your logic to handle the successful response here
        }
      } catch (error) {
        console.error('Error processing request:', error);
        // Add your logic to handle errors here
      }
    };

    fetchData();
  }, [url, options, router, onDataReceived]);

  // You can return additional data or state here if needed
}

then use it like
 const apiUrl = 'https://api.example.com/data';
  const fetchOptions = {
    method: 'GET',
    headers: {
      'Content-Type': 'application/json',
      // Add other headers as needed
    },
    // Add other fetch options as needed
  };

  // Define a callback function to run on received data
  const handleDataReceived = (data) => {
    // Add your logic to handle the received data here
    console.log('Handling received data:', data);
  };

  // Use the custom fetch hook with the onDataReceived callback
  useCustomFetch(apiUrl, fetchOptions, handleDataReceived);
Basset Artésien NormandOP
Thanks!