In this post let us see how we can leverage the power of Express with a sprinkling of Alpine JS to create a quick URL shortener application.
But, why?
Express is the most popular server-side framework and my “go to” choice for creating anything really quick. Building a front-end for Express is as easy as using handlebars (or anything really) that goes in HTML served by Express. But that lacks a “nice” user experience.
AlpineJS is a small and sweet framework that will go places. It follows Vue in many respects (and tries to achieve parity in a lot of respects), but does not want to be a full-scaled framework. Rather, it sits happily with other code to provide user interactivity to your front-end.
Depending on what you are set to do, AlpineJS can be a good choice for your back-end application.
Use Case: Shorten URL
The premise is simple.
- User supplies URL (e.g.
http://twitter.com/techformist
) - We shorten it and give it back to user (e.g.
https://go.co/tf
, assuminggo.co
is our domain) - Anyone can use the short URL. The request just bounces off our server to navigate to the longer web address
For simplicity we will ignore any authentication requirements.
We will use ExpressJS as the backend because that is one of the quicker and nicer frameworks to work with. We will use SQLite as the database.
Create a Basic Express App with SQLite DB
We will start building with some basic code. No generators, no fluff.
Create a new folder for your project and initialise using npm
.
|
|
npm init
will create package.json
in your project folder. Edit the file to include scripts to run your application.
|
|
Install express
, sqlite3
and a few useful libraries for security.
|
|
Install nodemon
so that our express application gets restarted automatically every time there is a change. This is useful during development.
|
|
Create a new file server.js
- this will be our main Express file. Let us bring in express
and friends.
|
|
Include logic to initialise database.
|
|
SQLite is just a file at heart (which database isn’t?). The above logic checks for a file called db/data.sqlite
. If the file does not exist, SQLite takes care of creating a new file. db.run
is used to run a SQL statement.
We will execute an SQL to create a table called urls
if it doesn’t already exist. There are three columns in this table -
url
- long form URL supplied by userslug
- key part of short-form URL. Can be supplied by user or we generate oneclicks
- no. of clicks on the short URL
Initialise express.
|
|
Include a test statement to show a message for a request.
|
|
.. and an error function to process any errors anywhere.
|
|
The basic Express application is now ready!
You can run the application using -
|
|
This should print a message - Listening on port 3000.
Send a POST
request using your favourite API testing tool to see "Hello, world"
message in response.
Define APIs in your Express Application
Before we go ahead with the API request/response, let use define a valid structure for the expected input.
|
|
We will have three services -
- Create new “short URL”
- Navigate user to the long URL when a valid short URL is provided
- List existing short URLs
This is also a good time to remember that we need to generate a random string if user does not provide the “slug” for the short URL. This can be done in a number of ways.
We will use a package called crypto-random-string
. Let us install the package.
|
|
Alternatively, you can use -
Let us start coding in the services.
Create new “short URL”
Create a new short URL for the user-provided URL.
- The generated short URL will be the combination of our domain (where the Express application is running) + a short slug.
- Slug is provided in request. It is optional, generate a URL-safe slug if not provided
- Store long form URL and the slug in the database
|
|
It is time to test this out!
Send a request to http://localhost:3000/new
like so -
|
|
You should receive this beautiful response -
|
|
Your short URL generation is ready, onwards to doing something with this request.
Navigate user to long URL
With the previous service the user received this short URL http://localhost:3000/ro0wgfvwxg
, which can now be happily shared by her to thousands of people.
When these people use the URL in a browser, the request is sent to our server. This can be fulfilled by a service that will fetch the long-form URL from the given short URL, and automatically navigate users to the correct destination.
This is easier than it looks.
|
|
The above code should do the trick. But, let’s improve that a bit more -
- add error handling - navigate user to an error page if slug is not found
- add logic to count number of clicks. Each time anyone uses the URL, the number of clicks will be incremented
|
|
Now, try navigating to https://localhost:/ro0wgfvwxg
in the browser. You should be navigated to the correct URL http://google.com
.
List URLs
Let us code the last of the services - list all URLs in the database.
This service is similar to the previous one, except that we run a simpler query to fetch all URLs and return them to the caller.
|
|
Try it! A request to https://localhost:3000/list
should return all the URLs from the database.
|
|
Your backend application is now fully ready to take on the world.
Front-end for Shorten URL Application
Create a simple HTML file index.html
in the project root, which will contain the whole of our frontend. Include AlpineJS from CDN.
|
|
Let us code some CSS since no one likes to see default styling. Since I am too lazy to do the complete styling by myself (capability aside), I will use a simple CSS framework called “MVP.css”.
Include MVP.css and a custom CSS (for minimal style changes) in the HTML head.
|
|
Create folders in the project root.
|
|
We can use powerful functions to bind HTML elements to backend. Let us create a form and the necessary objects that will act as the container for all functionality.
|
|
Note that -
process()
will provide the infrastructure for AlpineJS. You can define JS variables, functions and more withinprocess
functionx-model
binds the HTML element to the backend variable (for e.g.url
). This is similar tov-model
in Vue
Express serves the HTML file by default when we navigate to https://localhost:3000/
. Navigate to this URL in the browser to see your application in action.
Let us add functionality to allow user to send request to Express and see results.
Add a button that sends data to backend Express, and elements to show results (or error). Input below code before the ending </form>
element.
|
|
Add the corresponding functions and variables in process
.
data
to store the response URL list anderror
to store errorshortenURL
- a function that invokes ournew
service to shorten a given URL
The complete <script>
element is below -
|
|
Voila, your application is ready just like that.
Complete code is at this Github repo.
The End
Building applications with Express is fun, and libraries like Alpine make the user experience fun too. I have to say - I am quite smitten this smart library.