Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Next.js Tutorial
  • Next.js Components
  • Next.js Functions
  • Next.js Deployment
  • Next.js Projects
  • Next.js Routing
  • Next.js Styles
  • Next.js Server-Side Rendering
  • Next.js Environment Variables
  • Next.js Middleware
  • Next.js Typescript
  • Next.js Image Optimization
  • Next.js Data Fetching
Open In App
Next Article:
Contact Us Form using Next.js
Next article icon

URL Shortener Service with NextJS

Last Updated : 14 Mar, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In this article, we will explore the process of building a URL shortener service using NextJS that takes a long URL and generates a shorter, more condensed version that redirects to the original URL when accessed. This shortened URL is typically much shorter and easier to share, especially in situations where character count is limited, such as in social media posts or text messages.

Output Preview: Let us have a look at how the final output will look like.

Screenshot-(20)

Prerequisites:

  • NPM & NodeJS
  • ReactJS
  • ReactJS Hooks
  • NextJS

Approach to Create URL Shortener Service:

  • React component named Home manages URL shortening.
  • Uses useState hook to manage state for original URL and shortened URL.
  • shortURL function handles form submission, sending request to TinyURL API.
  • If successful, sets state with shortened URL; else, shows error alert.
  • Renders input field and submit button for entering URL.
  • Displays shortened URL with anchor tag for opening in new tab.
  • Uses security attributes target="_blank" rel="noopener noreferrer" for link.

Steps to create the URL Shortener Service:

Step 1: Create a application of NextJS using the following command.

npx create-next-app@latest url-shortener

Step 2: Navigate to project directory

cd url-shortener

Project Structure:

Screenshot-(22)

The updated dependencies in package.json file will look like:

"dependencies": {
"react": "^18",
"react-dom": "^18",
"next": "14.1.3"
}

Example: Below are the files which describes the basic implementation of URL Shortener Service.

CSS
/* globals.css */ main {     display: flex;     flex-direction: column;     align-items: center;     justify-content: center;     height: 100vh;     padding: 0 20px;     text-align: center;   }      h1 {     color: green;     font-size: 2rem;     margin-bottom: 20px;   }      form {     display: flex;     flex-direction: column;     align-items: center;   }      input {     width: 100%;     padding: 10px;     margin-bottom: 10px;   }      button {     padding: 10px 20px;     background-color: #007bff;     color: #fff;     border: none;     cursor: pointer;   }      button:hover {     background-color: #0056b3;   }      a {     color: #007bff;     text-decoration: none;   }      a:hover {     text-decoration: underline;   }    
JavaScript
// page.js 'use client' import { useState } from "react"; import "./globals.css";  export default function Home() {     const [url, setUrl] = useState("");     const [shortenedUrl, setShortenedUrl] = useState("");      async function shortURL(e) {         e.preventDefault();         const response = await             fetch(` https://tinyurl.com/api-create.php?url=${encodeURIComponent(url)}`);         if (response.ok) {             const data = await response.text();             setShortenedUrl(data);         }         else {             alert("Error shortening URL");         }     }      return (         <main>             <h1>GeeksForGeeks</h1>             <h2>URL Shortener</h2>             <form onSubmit={shortURL}>                 <input                     type="text"                     placeholder="Enter URL"                     value={url}                     onChange={(e) => setUrl(e.target.value)}                 />                 <button type="submit">Shorten</button>             </form>             {shortenedUrl && (                 <div>                     <p>Shortened URL:</p>                     <a href={shortenedUrl} target="_blank"                         rel="noopener noreferrer">                         {shortenedUrl}                     </a>                 </div>             )}         </main>     ); } 

Start your application using the below command.

npm run dev

Output: Naviage to the URL http://localhost:3000.


gfgsrt


Next Article
Contact Us Form using Next.js

G

ghuleyogesh
Improve
Article Tags :
  • Project
  • Web Technologies
  • ReactJS
  • Dev Scripter
  • Next.js
  • Web Development Projects
  • Dev Scripter 2024
  • Next.js - Projects

Similar Reads

    Blogging Platform using Next JS
    In this project, we will explore the process of building The Blogging Platform with Next.js. Blogging Platform is a web application that allows users to create and publish blog posts. The platform provides a user-friendly interface for managing blog content and includes functionalities to create new
    5 min read
    How to Create Todo App using Next.js ?
    In this article, we will create a to-do application and understand the basics of Next.js. This to-do list can add new tasks we can also delete the tasks by clicking on them.Next.js is a widely recognized React framework that e­nables server-side­ rendering and enhance­s the developme­nt of interacti
    4 min read
    Document Management System using NextJS
    The Document Management System is a web application developed using Next.js, that allows users to efficiently manage their documents. The system provides features for uploading, organizing, and retrieving documents. Users can upload documents through the web interface, which are then stored in local
    5 min read
    Create a Quiz App with Next JS
    In this article, we’ll explore the process of building a Quiz App utilizing NextJS. The quiz app provides users with a series of multiple-choice questions with options. Users can select the option and move to the next question. At the end, the user will be able to see the analysis of the quiz.Output
    5 min read
    E-commerce Dashboard with NextJS
    This project is an E-commerce Dashboard built with Next.js, providing features such as a dynamic sidebar, responsive navigation, order analytics, and most sold items of the week. It shows various features such as product analytics, order management, and user interaction. Output Preview: Prerequisite
    11 min read
    Social Networking Platform using Next.js
    The Social Networking Platform built with NextJS is a web application that provides users the functionality to add a post, like a post, and be able to comment on it. The power of NextJS, a popular React framework for building server-side rendered (SSR) and statically generated web applications, this
    8 min read
    URL Shortener Service with NextJS
    In this article, we will explore the process of building a URL shortener service using NextJS that takes a long URL and generates a shorter, more condensed version that redirects to the original URL when accessed. This shortened URL is typically much shorter and easier to share, especially in situat
    2 min read
    Contact Us Form using Next.js
    Creating a Contact Us form in Next.js involves setting up a form component, handling form submissions, and potentially integrating with a backend service or API to send the form data. In this article, we will create a Contact Us Form with NextJS.Output Preview: Let’s have a look at what our final pr
    6 min read
    Blogging Platform using Next JS
    In this project, we will explore the process of building The Blogging Platform with Next.js. Blogging Platform is a web application that allows users to create and publish blog posts. The platform provides a user-friendly interface for managing blog content and includes functionalities to create new
    5 min read
    Music Player App with Next.js and API
    In this tutorial, we'll create a Music Player App using NextJS, a React framework. Explore frontend development, API integration, and UI design to build a user-friendly app for seamless music enjoyment. Join us in harmonizing code and creativity to craft an engaging Music Player App with NextJS in t
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences