Build a Next.js Interactive Web-Based URL Analyzer

Written by

in

In the digital age, understanding the structure and performance of web URLs is crucial for SEO, web development, and general online navigation. A URL analyzer provides valuable insights into the components of a URL, such as the protocol, domain, path, and query parameters. This information is essential for debugging, optimizing web pages, and even identifying potential security risks. Building a URL analyzer allows you to learn about Next.js, a powerful React framework, while creating a practical tool that you can use daily.

Why Build a URL Analyzer?

As a developer, you often encounter URLs, whether you’re building APIs, analyzing website traffic, or simply troubleshooting a broken link. A URL analyzer simplifies this process by breaking down a complex URL into its individual parts. This project provides a hands-on opportunity to:

  • Learn Next.js Fundamentals: You’ll become familiar with core concepts such as components, state management, and routing.
  • Understand URL Structure: Gain a deeper understanding of how URLs are constructed and how they work.
  • Improve Debugging Skills: Quickly identify issues with URLs, such as incorrect paths or missing parameters.
  • Enhance SEO Knowledge: Analyze URLs for SEO best practices, like the presence of keywords in the URL path.
  • Build a Useful Tool: Create a practical tool that you can use for your projects or share with others.

What We Will Build

We’ll create a simple, yet functional, URL analyzer using Next.js. The tool will take a URL as input and display its various components in a clear, easy-to-understand format. This will include:

  • Protocol: (e.g., http, https)
  • Domain: (e.g., example.com)
  • Path: (e.g., /about, /blog/post-1)
  • Query Parameters: (e.g., ?id=123&sort=date)
  • Hash: (e.g., #section1)

Prerequisites

Before we get started, make sure you have the following installed:

  • Node.js and npm (or yarn): You’ll need these to manage project dependencies and run the development server.
  • A Code Editor: Such as Visual Studio Code, Sublime Text, or Atom.
  • Basic Understanding of HTML, CSS, and JavaScript: Familiarity with these languages will be helpful.

Step-by-Step Guide

1. Setting Up the Next.js Project

First, let’s create a new Next.js project. Open your terminal and run the following command:

npx create-next-app url-analyzer

This command will create a new directory called url-analyzer with the basic structure of a Next.js application. Navigate into the project directory:

cd url-analyzer

Now, start the development server:

npm run dev

Your Next.js application should be running on http://localhost:3000.

2. Creating the Input Field and Display Area

Let’s modify the pages/index.js file to include an input field for the URL and an area to display the analyzed results. Open pages/index.js in your code editor. Replace the existing code with the following:

import { useState } from 'react';

export default function Home() {
  const [url, setUrl] = useState('');
  const [urlData, setUrlData] = useState(null);

  const handleAnalyze = async () => {
    // Implementation will go here
  };

  return (
    <div className="container">
      <h1>URL Analyzer</h1>
      <input
        type="text"
        value={url}
        onChange={(e) => setUrl(e.target.value)}
        placeholder="Enter URL"
      />
      <button onClick={handleAnalyze}>Analyze</button>
      {urlData && (
        <div className="results">
          <h2>Analysis Results</h2>
          <p>Protocol: {urlData.protocol}</p>
          <p>Domain: {urlData.domain}</p>
          <p>Path: {urlData.path}</p>
          <p>Query Parameters: {JSON.stringify(urlData.query, null, 2)}</p>
          <p>Hash: {urlData.hash}</p>
        </div>
      )}
    </div>
  );
}

In this code:

  • We import useState to manage the URL input and the analyzed data.
  • We create a state variable url to store the user’s input and urlData to store the parsed URL components.
  • We have an input field that updates the url state as the user types.
  • A button triggers the handleAnalyze function.
  • The results are displayed conditionally based on whether urlData has a value.

Let’s add some basic CSS to style the page. Create a file named styles/Home.module.css and add the following:

.container {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px;
  font-family: sans-serif;
}

input, button {
  margin: 10px;
  padding: 10px;
  font-size: 16px;
}

.results {
  border: 1px solid #ccc;
  padding: 20px;
  margin-top: 20px;
  width: 80%;
  max-width: 600px;
}

Then, import the CSS file into your pages/index.js file:

import styles from '../styles/Home.module.css';

And apply the styles to the relevant components:

<div className={styles.container}>
  <h1>URL Analyzer</h1>
  <input
    type="text"
    value={url}
    onChange={(e) => setUrl(e.target.value)}
    placeholder="Enter URL"
    className={styles.input}
  />
  <button onClick={handleAnalyze} className={styles.button}>Analyze</button>
  {urlData && (
    <div className={styles.results}>
      <h2>Analysis Results</h2>
      <p>Protocol: {urlData.protocol}</p>
      <p>Domain: {urlData.domain}</p>
      <p>Path: {urlData.path}</p>
      <p>Query Parameters: {JSON.stringify(urlData.query, null, 2)}</p>
      <p>Hash: {urlData.hash}</p>
    </div>
  )}
</div>

3. Implementing URL Parsing Logic

Now, let’s implement the handleAnalyze function to parse the URL. We’ll use the built-in URL constructor in JavaScript, which provides an easy way to extract URL components. Update the handleAnalyze function in pages/index.js:

const handleAnalyze = async () => {
  try {
    const parsedURL = new URL(url);
    const data = {
      protocol: parsedURL.protocol,
      domain: parsedURL.hostname,
      path: parsedURL.pathname,
      query: Object.fromEntries(parsedURL.searchParams),
      hash: parsedURL.hash,
    };
    setUrlData(data);
  } catch (error) {
    setUrlData(null);
    alert('Invalid URL');
  }
};

Here’s what this code does:

  • It attempts to create a new URL object using the input url.
  • If successful, it extracts the protocol, hostname (domain), pathname (path), searchParams (query parameters converted to an object), and hash.
  • It sets the urlData state with the parsed components.
  • If the URL is invalid (e.g., malformed), it catches the error, sets urlData to null, and displays an alert.

4. Testing the URL Analyzer

Save the pages/index.js file and open your browser at http://localhost:3000. Enter a URL in the input field (e.g., https://www.example.com/blog/article?id=123#section1) and click the