Build a Next.js Interactive Web-Based Cryptocurrency Price Alert System

Written by

in

In the fast-paced world of cryptocurrency, staying informed about price fluctuations is crucial. Missing a sudden surge or dip can mean lost opportunities or unexpected losses. Wouldn’t it be great to have a system that automatically notifies you when your favorite cryptocurrencies hit specific price targets? This tutorial will guide you through building a simple, yet effective, web-based cryptocurrency price alert system using Next.js. We’ll cover everything from fetching real-time crypto data to implementing user-friendly alert settings and sending notifications. This project is perfect for beginners to intermediate developers looking to expand their skills with practical, real-world applications.

Why Build a Crypto Price Alert System?

The cryptocurrency market operates 24/7, making it impossible to constantly monitor prices manually. A price alert system automates this process, saving you time and ensuring you never miss critical price movements. Whether you’re a seasoned trader or just starting, this system provides a valuable tool for informed decision-making. Imagine being able to set alerts for Bitcoin, Ethereum, and other coins, knowing you’ll be notified instantly when a target price is reached. This project not only teaches you Next.js but also provides a practical solution to a common problem in the crypto space.

What We’ll Build

Our project will consist of the following key features:

  • Real-time Price Data Fetching: We’ll use a cryptocurrency API to retrieve up-to-the-minute price data for various cryptocurrencies.
  • User-Friendly Alert Settings: Users will be able to specify cryptocurrency, target price, and notification method (e.g., email or browser notification).
  • Alert Logic: The system will continuously monitor prices and trigger alerts when the set conditions are met.
  • Notification System: We’ll implement a notification system to alert users when a price target is reached.
  • Clean and Responsive UI: We’ll design a user interface that is easy to navigate and responsive across different devices.

Prerequisites

Before we dive in, ensure you have the following:

  • Node.js and npm (or yarn) installed: These are essential for running Next.js projects.
  • Basic knowledge of JavaScript and React: Familiarity with these technologies will be helpful, but we’ll explain the key concepts as we go.
  • A code editor: Visual Studio Code, Sublime Text, or any editor you prefer.

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 crypto-alert-system

This command sets up a new Next.js project named “crypto-alert-system”. Navigate into the project directory:

cd crypto-alert-system

Now, start the development server:

npm run dev

Open your browser and go to http://localhost:3000. You should see the default Next.js welcome page. This confirms that your project is set up correctly.

2. Installing Dependencies

We’ll need a few dependencies for our project. Install them using npm:

npm install axios react-toastify
  • axios: For making API requests to fetch cryptocurrency prices.
  • react-toastify: To display user-friendly notifications in the browser.

3. Fetching Cryptocurrency Data

We’ll use a cryptocurrency API to fetch real-time price data. There are several free and paid APIs available. For this tutorial, we’ll use a free API like CoinGecko (you’ll need to sign up for an API key if they require it). Replace the placeholder with the actual API endpoint.

Create a new file named `api.js` in the `utils` directory (create the directory if it doesn’t exist):

// utils/api.js
import axios from 'axios';

const API_URL = 'https://api.coingecko.com/api/v3'; // Replace with your API endpoint

export const getCryptoPrice = async (coinId) => {
  try {
    const response = await axios.get(`${API_URL}/simple/price?ids=${coinId}&vs_currencies=usd`);
    return response.data;
  } catch (error) {
    console.error('Error fetching crypto price:', error);
    return null;
  }
};

This `getCryptoPrice` function fetches the price of a specific cryptocurrency (e.g., “bitcoin”) in USD. Make sure to replace the placeholder API URL with a valid one. The `axios` library handles the HTTP request, and we parse the response data. Error handling is included to catch any issues during the API call.

4. Creating the Alert Form

Let’s create a form where users can set their price alerts. We’ll use React’s `useState` hook to manage the form state.

Modify the `pages/index.js` file:

// pages/index.js
import { useState, useEffect } from 'react';
import { ToastContainer, toast } from 'react-toastify';
import 'react-toastify/dist/ReactToastify.css';
import { getCryptoPrice } from '../utils/api';

const supportedCoins = ["bitcoin", "ethereum", "litecoin"]; // Add more coins as needed

export default function Home() {
  const [coin, setCoin] = useState('bitcoin');
  const [targetPrice, setTargetPrice] = useState('');
  const [alerts, setAlerts] = useState([]);
  const [currentPrices, setCurrentPrices] = useState({});

  useEffect(() => {
    const fetchPrices = async () => {
      const prices = {};
      for (const coinId of supportedCoins) {
        const priceData = await getCryptoPrice(coinId);
        if (priceData && priceData[coinId]) {
          prices[coinId] = priceData[coinId].usd;
        }
      }
      setCurrentPrices(prices);
    };

    fetchPrices();
    const intervalId = setInterval(fetchPrices, 10000); // Update prices every 10 seconds

    return () => clearInterval(intervalId);
  }, []);

  const handleAddAlert = (e) => {
    e.preventDefault();
    if (!coin || !targetPrice) {
      toast.error('Please fill in all fields.');
      return;
    }

    const newAlert = {
      coin,
      targetPrice: parseFloat(targetPrice),
      isTriggered: false,
    };
    setAlerts([...alerts, newAlert]);
    setTargetPrice('');
    toast.success('Alert set successfully!');
  };

  useEffect(() => {
    const checkAlerts = () => {
      alerts.forEach((alert, index) => {
        if (!alert.isTriggered && currentPrices[alert.coin] && currentPrices[alert.coin] >= alert.targetPrice) {
          toast.success(`Alert: ${alert.coin.toUpperCase()} reached ${alert.targetPrice} USD!`);
          const updatedAlerts = [...alerts];
          updatedAlerts[index] = { ...alert, isTriggered: true };
          setAlerts(updatedAlerts);
        }
      });
    };

    if (Object.keys(currentPrices).length > 0) {
      checkAlerts();
    }
  }, [alerts, currentPrices]);

  return (
    <div>
      
      <h1>Crypto Price Alert System</h1>
      
        <label>Coin:</label>
         setCoin(e.target.value)}>
          {supportedCoins.map(coin => (
            {coin.toUpperCase()}
          ))}
        

        <label>Target Price (USD):</label>
         setTargetPrice(e.target.value)} />

        <button type="submit">Set Alert</button>
      

      <h2>Current Prices</h2>
      <div>
        {Object.entries(currentPrices).map(([coinId, price]) => (
          <div>
            <span>{coinId.toUpperCase()}:</span> <span>${price ? price.toFixed(2) : 'Loading...'}</span>
          </div>
        ))}
      </div>

      <h2>Active Alerts</h2>
      <div>
        {alerts.map((alert, index) => (
          <div>
            <span>{alert.coin.toUpperCase()}:</span> <span>Target: ${alert.targetPrice}</span>
          </div>
        ))}
      </div>
    </div>
  );
}

Key improvements in this code:

  • `useState` Hooks: Manage the form input values (`coin`, `targetPrice`) and the list of alerts (`alerts`). The `currentPrices` state stores the latest prices fetched from the API.
  • `useEffect` Hook (Price Fetching): Fetches the current prices of the cryptocurrencies every 10 seconds. The `useEffect` hook with an empty dependency array (`[]`) ensures this happens only once when the component mounts. The interval is cleared when the component unmounts to prevent memory leaks.
  • `useEffect` Hook (Alert Checking): This `useEffect` hook is triggered whenever the `alerts` or `currentPrices` state changes. It iterates through the active alerts and checks if the current price of a coin has reached or exceeded its target price. If the condition is met, it displays a success toast notification using `react-toastify`. The alert’s `isTriggered` property is set to `true` to prevent the same alert from being triggered multiple times.
  • Form Handling (`handleAddAlert`): Handles the form submission. It prevents the default form submission behavior, validates the input fields, creates a new alert object, adds it to the `alerts` state, and clears the input field. It also displays a success toast notification.
  • Alert Display: Displays the active alerts in a user-friendly format.
  • Current Price Display: Displays the current prices of supported cryptocurrencies, updating in real-time.
  • Error Handling: Basic error handling is incorporated, such as checking for empty input fields and displaying toast notifications.
  • `react-toastify`: Provides a user-friendly way to display notifications when an alert is triggered or when errors occur.

5. Implementing Alert Logic

The core of the system is the alert logic. We’ll implement a function to check the current prices against the set target prices. This function will be called periodically, for example, every 10 seconds. When a target price is reached, we’ll display a notification to the user.

We’ve already included the alert logic within the `useEffect` hook in the previous code. This hook runs whenever the `alerts` or `currentPrices` state changes. Inside this hook:

  • We iterate over the `alerts` array.
  • For each alert, we check if the current price of the specified coin (fetched from `currentPrices`) has reached or exceeded the alert’s `targetPrice`.
  • If the condition is met, we use `react-toastify` to display a success notification.
  • To avoid duplicate notifications, we set a flag (e.g., `isTriggered`) on the alert object to indicate that it has already been triggered.

6. Adding Notifications

We’re using `react-toastify` for notifications, which are displayed in the browser. This provides a simple and effective way to alert the user. You can customize the notification messages and styles to suit your preferences.

The `ToastContainer` component from `react-toastify` is added to the main component to render the notifications. We also use `toast.success` and `toast.error` to display success and error messages, respectively.

7. Styling (Basic CSS)

Let’s add some basic styling to make the app more user-friendly. Create a file named `styles/Home.module.css` and add the following CSS:

/* styles/Home.module.css */
.container {
  width: 80%;
  margin: 20px auto;
  padding: 20px;
  border: 1px solid #ccc;
  border-radius: 5px;
  background-color: #f9f9f9;
}

h1 {
  text-align: center;
  margin-bottom: 20px;
}

.alert-form {
  display: flex;
  flex-direction: column;
  margin-bottom: 20px;
}

.alert-form label {
  margin-bottom: 5px;
  font-weight: bold;
}

.alert-form input, .alert-form select {
  padding: 8px;
  margin-bottom: 10px;
  border: 1px solid #ccc;
  border-radius: 4px;
}

.alert-form button {
  padding: 10px;
  background-color: #4CAF50;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.current-prices, .alerts-list {
  margin-bottom: 20px;
}

.price-item, .alert-item {
  display: flex;
  justify-content: space-between;
  padding: 10px;
  border: 1px solid #eee;
  border-radius: 4px;
  margin-bottom: 5px;
}

Import this CSS file into `pages/index.js`:

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

And apply the styles to the relevant elements in your JSX:

<div>...</div>

8. Testing and Refinement

Test the application thoroughly. Set alerts for different cryptocurrencies and price points. Verify that the alerts trigger correctly when the target prices are reached. Check for any errors in the console and address them. Refine the UI/UX based on your testing and feedback.

9. Deployment

Once you’re satisfied with your application, it’s time to deploy it. Next.js makes deployment easy. You can deploy to platforms like Vercel, Netlify, or AWS. Vercel is a popular choice because it’s optimized for Next.js.

To deploy to Vercel:

  • Create a Vercel account (if you don’t have one).
  • Connect your GitHub repository to Vercel.
  • Vercel will automatically build and deploy your application.
  • You’ll get a unique URL to access your deployed application.

Common Mistakes and How to Fix Them

  • Incorrect API Endpoint: Double-check the API endpoint you are using. Make sure it’s correct and that you have the necessary API key (if required).
  • CORS Errors: If you encounter CORS (Cross-Origin Resource Sharing) errors, it means the API you are calling doesn’t allow requests from your domain. You might need to configure CORS on the API server or use a proxy.
  • State Management Issues: Ensure your state variables (e.g., `alerts`, `targetPrice`) are updated correctly. Use the `useState` hook properly.
  • Notification Errors: If notifications aren’t displaying, check the browser’s console for any errors related to `react-toastify`. Make sure you’ve imported the necessary CSS.
  • API Rate Limits: Be mindful of API rate limits. If you exceed the limits, your API requests will be blocked. Consider implementing strategies like caching or using a different API.
  • Unnecessary Re-renders: Optimize your components to prevent unnecessary re-renders. Use `React.memo` for functional components or `shouldComponentUpdate` for class components to improve performance.
  • Missing Dependencies: Ensure you have all the necessary dependencies installed by checking your `package.json` file.

Key Takeaways

This tutorial has shown you how to build a web-based cryptocurrency price alert system using Next.js. You’ve learned how to fetch real-time data, implement user-friendly alert settings, and display notifications. You’ve also gained practical experience with state management, API calls, and UI design.

FAQ

  1. Can I add more cryptocurrencies? Yes, simply add the coin ID to the `supportedCoins` array and modify the API call to include the new coin.
  2. How can I improve the notification system? You can integrate with services like Twilio to send SMS notifications or use webhooks to trigger other actions.
  3. How can I persist the alerts? You can store the alerts in local storage or a database (e.g., using MongoDB or Firebase) to persist them across sessions.
  4. How do I handle API errors more gracefully? Implement more robust error handling, such as displaying error messages to the user and retrying failed requests.
  5. How can I make the UI more responsive? Use a CSS framework like Bootstrap or Tailwind CSS to create a responsive and mobile-friendly design.

This project serves as a solid foundation for building more advanced cryptocurrency applications. Remember to explore the various APIs, experiment with different features, and continuously refine your skills. The ability to react quickly to market changes is a core advantage in the crypto world, and this price alert system is your first step towards that goal. As you continue to build and refine your skills, you’ll be well-equipped to navigate the volatile world of cryptocurrencies with greater confidence and efficiency. The knowledge and experience gained from this project will also be valuable in various other web development projects.