Skip to content
  • Unlock Pro
  • Log in with GitHub
Solution
Submitted almost 3 years ago

IP Address tracker - Next.js, Tailwind CSS, Typescript

fetch, next, react, tailwind-css, typescript
exitsimulation•100
@exitsimulation
A solution to the IP Address Tracker challenge
View live sitePreview (opens in new tab)View codeCode (opens in new tab)

Solution retrospective


IP Address Tracker - Frontend Mentor Challenge

Solution with Next.js, Tailwind CSS and Typescript

For this solution to the Frontend Mentor - IP Address tracker challenge I used the npx create-next-app template as a base and customized it with Tailwind CSS support. Initially I was using Next.js 13 and the new app directory, however, Leaflet.js (which is used for rendering the live map) seems to have problems with this Next.js version or its experimental features. Thus, I rolled back to the old pages directory.

Map component with Leaflet.js

The map component needs to be dynamically loaded with next/dynamic because Leaflet.js needs access to the window object:

  const MapWithNoSSR = dynamic(() => import("../components/MapComponent"), {
    ssr: false,
  });

Querying the IP data

For the IP queries to https://geo.ipify.org I am using Vercel's useSWR hook and axios in combination with Next.js dynamic API routes.

useSWR needs a fetcher function which is a wrapper around the usual fetch method:

const fetcher = (url: string) => fetch(url).then((res) => res.json());

const { data, error } = useSWR("/api/ip/" + `${ipAddress}`, fetcher);

https://swr.vercel.app/

Data validation with regex pattern

For the data validation of the input field I am using the following regex pattern:

const regex_ipv4 =
"(([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\\.){3}([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])";

Get client IP address

export const getServerSideProps = async ({ req }: { req: NextApiRequest }) => {
    const forwarded = req.headers["x-forwarded-for"];

    const ip =
        typeof forwarded === "string"
            ? forwarded.split(/, /)[0]
            : req.socket.remoteAddress;

    console.log(ip);

    return {
        props: { ip },
    };
};
Code
Loading...

Please log in to post a comment

Log in with GitHub

Community feedback

No feedback yet. Be the first to give feedback on exitsimulation's solution.

Join our Discord community

Join thousands of Frontend Mentor community members taking the challenges, sharing resources, helping each other, and chatting about all things front-end!

Join our Discord

Stay up to datewith new challenges, featured solutions, selected articles, and our latest news

Frontend Mentor

  • Unlock Pro
  • Contact us
  • FAQs
  • Become a partner
  • Use cases

Explore

  • Learning paths
  • Challenges
  • Solutions
  • Articles

Community

  • Discord
  • Guidelines

For companies

  • Hire developers
  • Train developers
© Frontend Mentor 2019 - 2025
  • Terms
  • Cookie Policy
  • Privacy Policy
  • License