Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect Internet Explorer on Next.js (SSR)?

There is a project where we use Next.js. In this project, Internet Explorer view is in a very bad state due to various React.js packages. (For example: React-Slick settings, tag etc.)

I'm also thinking of something to check if the browser is IE but unfortunately the "react-device-detect" package didn't work as it is SSR.

Example:

import {isIE} from "react-device-detect" 

<section className="home">
    {isIE ? (
    <div>
      <p>Google Chrome, Firefox, etc...</p>
    </div>
  ) : (
    <div>
      <p>Internet Explorer</p>
    </div>
  )}
</section>

When I do console.log, it understands whether the browser is IE or not, but it does not fulfill its task. For example: If the browser is IE, we want to render "X", but both Chrome and IE render X.)

How can I detect that the browser is Internet Explorer and provide this browser specific control on Next.js (SSR)? Thanks.

like image 478
ogulcan Avatar asked Nov 17 '25 05:11

ogulcan


1 Answers

Why not simply do something like this:

export default function IndexPage({ isIE }) {
  return <div>Hello {isIE ? "IE" : "Modern Browsers"}!</div>;
}

export async function getServerSideProps({ req }) {
  return {
    props: {
      isIE: /MSIE|Trident/.test(req.headers["user-agent"])
    }
  };
}

Or maybe:

import { useEffect, useState } from "react";

export default function IndexPage() {
  const [isIE, setIsIE] = useState(false);

  useEffect(() => {
    setIsIE(/MSIE|Trident/.test(window.navigator.userAgent));
    return () => {};
  }, []);

  return <div>Hello {isIE ? "IE" : "Modern Browsers"}!</div>;
}

PS: IE users generally don't fake the user-agent headers, so the first should work fine for general users. Also, the second method will need efforts (during development) to manually check by running the website on IE as User-Agent Switcher just changes the headers. And, AFAIK services like Google Fonts too just check the headers and send the CSS accordingly. Also, I agree with Keith you should go with feature detection (and fallbacks) instead of selective rendering.

Side Note:

Please read Browser detection using the user agent for why serving different Web pages or services to different browsers is usually a bad idea.

~ MDN

like image 58
brc-dd Avatar answered Nov 19 '25 18:11

brc-dd