Build a Next.js Interactive Web-Based Simple Text Summarizer

Written by

in

In the digital age, we’re bombarded with information. Sifting through lengthy articles, reports, and documents to extract the core message can be a time-consuming task. Imagine a tool that could automatically condense any text into its most important points, saving you valuable time and effort. In this tutorial, we’ll build a simple yet effective text summarizer using Next.js, a powerful React framework, to create an interactive web application that does just that. This project is perfect for beginners and intermediate developers looking to expand their skills in web development, API integration, and natural language processing (NLP).

Why Build a Text Summarizer?

Text summarization has numerous practical applications. Consider these scenarios:

  • Research: Quickly grasp the essence of research papers and articles.
  • Content Curation: Generate concise summaries for social media posts or newsletters.
  • Information Overload: Digest large volumes of text efficiently.
  • Education: Help students understand complex topics faster.

By building this project, you’ll gain hands-on experience with:

  • Next.js fundamentals: setting up a project, creating components, and handling user input.
  • API integration: making requests to a text summarization API.
  • State management: managing the application’s data.
  • User interface (UI) design: creating a user-friendly interface.

Prerequisites

Before we dive in, ensure you have the following:

  • Node.js and npm: Installed on your machine. You can download them from nodejs.org.
  • A text editor: Such as Visual Studio Code, Sublime Text, or Atom.
  • Basic knowledge of JavaScript and React: Familiarity with these technologies will be helpful but not strictly required.
  • An API Key: You will need an API key from a text summarization service. We will use the free API from RapidAPI, but you can choose another one. Create an account at RapidAPI.com and subscribe to a text summarization API. Note the API endpoint and your API key; we’ll need them later.

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 text-summarizer

This command creates a new directory named “text-summarizer” with the basic structure of a Next.js application. Navigate into the project directory:

cd text-summarizer

2. Installing Dependencies

We’ll need to install a few dependencies for our project. We’ll use the `axios` library to make API requests.

npm install axios

3. Creating the UI Components

Let’s create the components for our user interface. We’ll need a component for the text input, a component to display the summary, and a button to trigger the summarization. We will modify the `app/page.js` file.

Replace the content of `app/page.js` with the following code:

'use client';

import { useState } from 'react';
import axios from 'axios';

export default function Home() {
  const [inputText, setInputText] = useState('');
  const [summary, setSummary] = useState('');
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');

  const API_ENDPOINT = 'YOUR_API_ENDPOINT'; // Replace with your API endpoint
  const API_KEY = 'YOUR_API_KEY'; // Replace with your API key

  const handleInputChange = (event) => {
    setInputText(event.target.value);
    setError(''); // Clear any previous errors on input change
  };

  const handleSubmit = async () => {
    if (!inputText.trim()) {
      setError('Please enter some text.');
      return;
    }

    setLoading(true);
    setSummary(''); // Clear previous summary
    setError(''); // Clear any previous errors

    try {
      const options = {
        method: 'POST',
        url: API_ENDPOINT,
        headers: {
          'Content-Type': 'application/json',
          'X-RapidAPI-Key': API_KEY,
          'X-RapidAPI-Host': 'YOUR_API_HOST' // Replace with your API host
        },
        data: { text: inputText, max_length: 150 }
      };

      const response = await axios.request(options);
      setSummary(response.data.summary_text);
    } catch (error) {
      console.error(error);
      setError('An error occurred while summarizing the text.');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div>
      <h1>Text Summarizer</h1>
      {error && <p>{error}</p>}
      <textarea rows="5" />
      <button disabled="{loading}">
        {loading ? 'Summarizing...' : 'Summarize'}
      </button>
      {summary && (
        <div>
          <h2>Summary:</h2>
          <p>{summary}</p>
        </div>
      )}
    </div>
  );
}

In this code:

  • We import `useState` from React to manage the state of our components.
  • We use `axios` to make API requests to the text summarization service.
  • We define state variables: `inputText` to store the user’s input, `summary` to store the generated summary, `loading` to indicate the summarization is in progress, and `error` to display any error messages.
  • `handleInputChange` updates the `inputText` state as the user types.
  • `handleSubmit` is called when the user clicks the “Summarize” button. It makes the API call and updates the `summary` state with the summarized text.
  • The UI consists of a textarea for input, a button to trigger summarization, and a section to display the summary.

Important: Replace `YOUR_API_ENDPOINT`, `YOUR_API_KEY`, and `YOUR_API_HOST` with your actual API endpoint, API key, and API host from the text summarization service you choose. The `max_length` parameter in the API request controls the length of the summary (in words), adjust as needed.

4. Styling with Tailwind CSS (Optional)

For styling, we’ll use Tailwind CSS, a utility-first CSS framework. If you didn’t choose the “Tailwind CSS” option during the project setup, you can add it now. Run the following commands in your terminal:

npm install -D tailwindcss postcss autoprefixer
npx tailwindcss init -p

This will install the necessary packages and create `tailwind.config.js` and `postcss.config.js` files. Next, configure Tailwind in your `tailwind.config.js` file. Add the following to the `content` array:

/** @type {import('tailwindcss').Config} */
module.exports = {
  content: [
    './app/**/*.{js,ts,jsx,tsx,mdx}',
    './components/**/*.{js,ts,jsx,tsx,mdx}',
    // Or if using `src` directory:
    './src/**/*.{js,ts,jsx,tsx,mdx}',
  ],
  theme: {
    extend: {
      // ...
    },
  },
  plugins: [],
}

Then, in your global CSS file (usually `app/globals.css` or `src/app/globals.css`), add the following directives:

@tailwind base;
@tailwind components;
@tailwind utilities;

Now, you can use Tailwind CSS classes in your React components. The code example above already includes some basic Tailwind CSS classes for styling. Feel free to customize the styling further to suit your preferences.

5. Running the Application

To run your application, execute the following command in your terminal:

npm run dev

This will start the development server, and you can access your application in your web browser at `http://localhost:3000`. Enter some text into the text area, click the “Summarize” button, and you should see the summary displayed below.

Common Mistakes and Troubleshooting

Here are some common mistakes and how to fix them:

  • API Key Errors: Double-check that you have entered your API key correctly in the code. Also, make sure that your API key is valid and hasn’t expired.
  • CORS Errors: If you encounter CORS (Cross-Origin Resource Sharing) errors, it means your browser is blocking the API request. This often happens because the API server and your Next.js application are running on different domains. You might need to configure CORS settings on your API provider’s side or use a proxy server to forward requests from your Next.js app to the API.
  • Incorrect API Endpoint: Verify that the API endpoint is correct. Typos in the endpoint can cause the API request to fail.
  • Network Errors: Ensure you have an active internet connection.
  • Missing Dependencies: Make sure you have installed all the necessary dependencies, particularly `axios`.
  • Incorrect Data Format: The API may require a specific data format (e.g., JSON) in the request body. Ensure that you are sending the data in the correct format.

Enhancements and Next Steps

This is a basic text summarizer. You can enhance it further by adding these features:

  • Error Handling: Implement more robust error handling to provide better feedback to the user.
  • Summary Length Control: Allow the user to specify the desired length of the summary.
  • Multiple Summarization Algorithms: Integrate different summarization algorithms and allow the user to choose their preferred method.
  • User Interface Improvements: Enhance the UI with better styling, loading indicators, and a more intuitive design.
  • Text Preprocessing: Implement text preprocessing techniques, such as removing stop words or stemming words, to improve summarization accuracy.
  • Support for Different Languages: Integrate a language detection feature and support summarization for multiple languages.
  • Integration with Other Services: Connect the summarizer with other services, such as a note-taking app or a content management system.

Summary / Key Takeaways

In this tutorial, we’ve built a functional text summarizer application using Next.js. We’ve covered the essential steps, from setting up the project and installing dependencies to creating UI components, integrating with an API, and handling user input. You’ve learned how to make API requests, manage application state, and build a user-friendly interface. Remember to replace the placeholder API endpoint, API key, and API host with your actual values. This project provides a solid foundation for understanding how to build interactive web applications and integrate external APIs. The ability to automatically summarize text is a valuable skill in today’s information-rich world, and this project serves as a practical example of how to implement this functionality. By expanding upon this foundation, you can create even more sophisticated and useful applications.

Furthermore, consider experimenting with different text summarization APIs to compare their performance and features. Explore different UI libraries and frameworks to enhance the design and user experience of your application. The possibilities are endless, and the knowledge gained from this project can be applied to many other web development scenarios. The ability to quickly extract the essence of any text is a powerful tool, and now you have the skills to create your own solution.