This is a basic Express application that includes a URL shortener service. The application is written in JavaScript and uses npm for package management. This project implements a simple URL shortener service using Node.js, Express, and PostgreSQL.
The application currently has two routes:
POST /shorten: This route accepts a URL and returns a shortened URL. Currently, it returns a static shortened URL.GET /:shortUrl: This route accepts a shortened URL and redirects to a static URL.
The short URL mappings are stored in a PostgreSQL database.
POST /shorten
- Accepts a JSON body containing a valid URL.
- Checks if the URL already exists in the database.
- If it does, returns the same short URL.
- If not, generates a new unique short code.
- Stores the short_url and original_url in the database.
- Returns the shortened URL.
GET /:shortUrl
- Looks up the short code in the database.
- Redirects to the original URL if found.
- Returns 404 if not found.
-
Open the repository in Codespaces
Click
Code → Create Codespaceon main. -
Install dependencies
npm installsudo apt updatesudo apt install -y postgresql-client
-
Start PostgreSQL using Docker (inside Codespaces)
docker compose up -dConfirm it’s running:
docker ps -
Connect to PostgreSQL
psql -U urluser -h localhost -d urlshortenerPassword:
urlpass -
Create the required table
CREATE TABLE urls ( id SERIAL PRIMARY KEY, short_url VARCHAR(10) UNIQUE NOT NULL, original_url TEXT NOT NULL ); -
Start the application
npm startCodespaces will prompt you to make port 3000 public.
-
Click Make
Public → Open in Browser. -
Copy the 3000 port URL for testing.
-
Your API base URL will look like:
https://<your-id>-3000.app.github.dev
-
-
Test
POST /shortenMethod: POST
Go to Ports and turn port 3000 public and copy the local address - this will be the URL:
URL:
https://<your-id>-3000.app.github.dev/shortenBody → raw → JSON{ "url": "https://google.com" }Example Response:
{ "shortUrl": "https://<your-id>-3000.app.github.dev/AbC123" }Sending
"https://google.com"again returns the same short URL. -
Test
GET /:shortUrlMethod: GET
URL:
https://<your-id>-3000.app.github.dev/AbC123Expected result: Redirect
Browser takes you to
https://google.comIn Postman, turn Follow redirects OFF to see the redirect header.
-
Testing invalid inputs
Missing body:
{}Returns:
400 Bad RequestInvalid URL:
{ "url": "not-a-url" }Returns:
400 Bad Request
To delete all stored URLs: DELETE FROM urls;