Ever since the dawn of the internet age, links have played an integral part in how we interact and visit web pages. It has acted as a means of access to various resources online. Its human-friendly readable format as opposed to knowing a webpage's actual IP address has contributed immensely to its broad usage.
Its popularity brought with it some slight issues, as more people started creating and hosting websites for their various needs, ranging from a company to blogs, to events, there has been a rapid increase in domain name/URLs. People now have to remember long URLs in order to visit sites, later. This is one major issue that URL Shortener came to eliminate.
Simply put, a URL shortener is a service that reduces the length of a URL. It achieves this by saving this URL to its records, assigning an alias (short text) to it, then redirecting any request made to this alias on its record to the host URL (Webpage).
This tutorial will show you how to build a URL Shortener Service using Next.js and Tailwind CSS for frontend and Strapi Headless CMS for backend. You can find the link to the completed frontend code here and as well as the completed backend code here.
It is necessary that before we proceed further into this article, we have a clearer understanding of what a URL Shortener does. Some of the advantages include:
Before starting this tutorial, you need to have:
Next.js is an awesome React framework for building highly dynamic applications. It comes with pre-rendering, server-side rendering, automatic code-splitting amongst many other great features out of the box.
Tailwind CSS is a utility-first CSS framework for rapidly building custom user interfaces. With Tailwind CSS, we write our CSS directly in our HTML classes. This is quite useful as we don't need to import an external stylesheet or use a separate library for UI designs.
Strapi is a Node.js open-source headless CMS that allows us to develop APIs and manage content easily without the hassle of building out a project from scratch. It allows for customization and self-hosting as opposed to the rigid traditional CMS we are used to.
We can easily build out APIs faster and consume the contents via APIs using any REST API client or GraphQL.
To set up a new Strapi Project is quite straightforward as running these few commands:
1npx create-strapi-app strapi-tutorial-shortner --quickstart
Change strapi-tutorial-shortner
to the preferred name of your project.
This would install and create a Strapi project locally.
After installation, the browser would open a page on localhost:1337, which would prompt to set up the first admin account to proceed with Strapi.
Next, we will create a new collection type that will store the details of each question and their respective answers.
Hence, we create a collection type called shortner
that has these four fields fields: alias
, url
, visit
, user
.
Clicking “Continue” would bring up another screen to select the fields for this collection. Choose the “Text” field from the list and provide alias
as its name.
Next, we select the Short Text
type in the Base Settings, as alias
is meant to be a short string.
Next, we proceed to the “Advanced settings” tab and check the “Required field” box to ensure this field is required. Also, we check the “Unique field” box to prevent having the same alias in our record.
We click on the Add another field to add the answer field. Below is a table showing the properties for all the fields we need in this collection:
Field Name | Field Type | Required | Unique |
---|---|---|---|
alias | Short text | true | true |
url | Short text | true | false |
visit | Number (integer) | false | false |
user | Number (integer) | true | false |
By default, whenever you create an API, they’re all going to be restricted from public access. We need to tell Strapi that you’re okay with exposing these checked endpoints to the public. Go to Settings > Users & Permissions Plugin ** > Roles and click to edit the Public Role. Next, scroll down to Permissions > Shortner and tick the find checkbox.
We would also be exposing some endpoints to the authenticated user. Click the “Go Back” button and then click edit the Authenticated Role. The image below shows the endpoints which would be exposed to the authenticated user: **
We customize the shortner
controller which is found at src/api/shortner/controllers/shortner.js
to add more functionality to it, to cater to our needs.
For the find
method, we have the following scenarios:
shortner
collection to track the visit.For the create
method; we use it to create a new record as well as assign the user field in the shortner
collection to the authenticated user’s ID. Hence only authenticated users have access to this endpoint.
For the delete
method; we use it to remove a record from the shortner
collection, only a user that created a record is allowed to delete it. That also means only authenticated users have access to this endpoint.
Hence replace the code of the file with the code below:
1 'use strict';
2 /**
3 * shortner controller
4 */
5 const { createCoreController } = require('@strapi/strapi').factories;
6 module.exports = createCoreController('api::shortner.shortner', ({ strapi }) => ({
7 async find(ctx) {
8 let { query } = ctx;
9 const user = ctx.state.user;
10 let entity;
11 if (user) {
12 query = { user: { '$eq': user.id } }
13 entity = await strapi.service('api::shortner.shortner').find({ filters: query });
14 } else {
15 query = { alias: { '$eq': query.alias } }
16 entity = await strapi.service('api::shortner.shortner').find({ filters: query });
17 if (entity.results.length !== 0) {
18 let id = entity.results[0].id
19 let visit = Number(entity.results[0].visit) + 1
20 await strapi.service('api::shortner.shortner').update(id, { data: { visit } });
21 }
22 }
23 const sanitizedEntity = await this.sanitizeOutput(entity, ctx);
24 return this.transformResponse(sanitizedEntity);
25 },
26 async create(ctx) {
27 const { data } = ctx.request.body;
28 const user = ctx.state.user;
29 let entity;
30 data.user = user.id
31 entity = await strapi.service('api::shortner.shortner').create({ data });
32 const sanitizedEntity = await this.sanitizeOutput(entity, ctx);
33 return this.transformResponse(sanitizedEntity);
34 },
35 async delete(ctx) {
36 let { id } = ctx.params;
37 const user = ctx.state.user;
38 let entity;
39 let query = { user: { '$eq': user.id }, id: { '$eq': id } }
40 entity = await strapi.service('api::shortner.shortner').find({ filters: query });
41 if (entity.results.length === 0) {
42 return ctx.badRequest(null, [{ messages: [{ id: 'You can delete someone else content' }] }]);
43 }
44 entity = await strapi.service('api::shortner.shortner').delete(id);
45 const sanitizedEntity = await this.sanitizeOutput(entity, ctx);
46 return this.transformResponse(sanitizedEntity);
47 },
48 }));
Creating a Next.js app
To create a Next.js app, open your terminal, cd
into the directory you’d like to create the app in, and run the following command:
1npx create-next-app -e with-tailwindcss nextjs-shortner
This would also configure Tailwind CSS with the project.
Running the Next.js Development Server
Next, we cd
into the newly created directory, in our case that would be nextjs-``shortner
:
1 cd nextjs-shortner
After which we start up the development server by running this command:
1 npm run dev
If everything was set up fine, the Next.js server should now be running on localhost:3000 and we should see the following page on our browser:
Next, we open up any text editor of our choice to write code for the rest of the application. Open up the installed project and we should have a folder structure such as this:
To begin the design of the interface, we would remove all of the code in the index.js
file and add the code below:
1 import React, { useContext, useEffect } from 'react';
2 import MyContext from '../lib/context';
3 import { useRouter } from "next/router";
4 export default function Home() {
5 const { isLoggedIn, user } = useContext(MyContext)
6 const router = useRouter()
7 useEffect(() => {
8 if (isLoggedIn) {
9 return router.push("/dashboard");
10 }
11 return router.push("/login");
12 }, [isLoggedIn])
13 return null
14 }
The above code makes use of React Context API to check if the user is authenticated. This determines which page gets shown to the user.
As can also be seen, we are importing a context
file from the lib
folder. We need to create this file. Go to the root of the project and create a folder called lib
, then create a file called context.js
in it.
Inside this context.js, we create the context
, and also assign the default value of false
to isLoggedIn
.
1 import React from 'react';
2 const MyContext = React.createContext({ isLoggedIn: false });
3 export default MyContext;
Next, we head straight to create the two files we would conditionally be redirecting to the Login
and Register
files.
Next.js creates routes for files under the pages
directory. The route points to the files themselves, their documentation explains it quite well. This means if we created a file called dashboard.js
in the pages
directory, we can access it by visiting localhost:3000/dashboard
without needing to create an additional routing mechanism. Great right?
So, we simply create the two files (Login and Register) in this pages
directory.
However, before we dive into these two pages, we would need to first update the content of the _app.js
page.
This page is used by Next.js to initialize other pages, so we could use it to achieve persistent layout between pages, custom error handling, and in our case, keeping a global state among pages. Read more about this page here.
Create an _app.js
file if it doesn't exist in the pages
director. Remove everything in it and replace its code with the code below:
1 import React, { useState, useEffect } from 'react';
2 import MyContext from '../lib/context';
3 import Cookie from "js-cookie";
4 import 'tailwindcss/tailwind.css'
5 export default function _App({ Component, pageProps }) {
6 const [user, setUser] = useState(null)
7 const [urls, setUrls] = useState([])
8
9 useEffect(() => {
10 const jwt = Cookie.get("jwt");
11 if (jwt) {
12 fetch(`${process.env.NEXT_PUBLIC_API_URL}/api/users/me`, {
13 headers: {
14 Authorization: `Bearer ${jwt}`,
15 },
16 }).then(async (res) => {
17 if (!res.ok) {
18 Cookie.remove("jwt");
19 setUser(null);
20 }
21
22 const user = await res.json();
23 setUser(user);
24 });
25 }
26 }, [])
27 return (
28 <MyContext.Provider
29 value={{
30 user: user,
31 isLoggedIn: !!user,
32 setUser,
33 setUrls,
34 urls
35 }}
36 >
37 <Component {...pageProps} />
38 </MyContext.Provider>
39 )
40 }
The above code simply wraps itself around all pages and handles the global state by using React Context API.
We also use the js-cookie
npm package to store our token, to persist a session even when the user refreshes the page.
To get it installed, we run the npm i js-cookie
command.
Then we import it into our file.
1import Cookie from "js-cookie";
We make use of the useEffect
hook to check if there is a stored token (meaning the user is logged in). If a token is found, we make a request to the Strapi API to get the details of this user. If there are no errors, we store the user in the user
state, else we delete the token and assign null
to the user
state.
1 useEffect(() => {
2 const jwt = Cookie.get("jwt");
3 if (jwt) {
4 fetch(`${process.env.NEXT_PUBLIC_API_URL}/api/users/me`, {
5 headers: {
6 Authorization: `Bearer ${jwt}`,
7 },
8 }).then(async (res) => {
9 if (!res.ok) {
10 Cookie.remove("jwt");
11 setUser(null);
12 }
13 const user = await res.json();
14 setUser(user);
15 });
16 }
17 }, [])
As can also be seen we have two states, user
and urls
, created using the useState
hook. We have seen the use of the user
state already, we use the urls
state to store the array of shorteners that we got from the Strapi API.
Lastly, we wrap the Component
with the Context API provider, similar to how we do it in Redux. Next, we set the values of the Context API to our state variables as well as functions such as setUrls
, setUser
so that other pages/components
would be able to access them.
Finally, we create a new variable called isLoggedIn
, this would be used to check if there exists an authenticated user.
1 return (
2 <MyContext.Provider
3 value={{
4 user: user,
5 isLoggedIn: !!user,
6 setUser,
7 setUrls,
8 urls
9 }}
10 >
11 <Component {...pageProps} />
12 </MyContext.Provider>
13 )
Now, we would go on to create the Register
file. Add the content below to the newly created pages/register.js
file:
1 import Head from 'next/head'
2 import Link from 'next/link'
3 import React, { useState, useContext, useEffect } from 'react';
4 import MyContext from '../lib/context';
5 import { register } from '../lib/auth'
6 import { useRouter } from "next/router";
7 export default function Register() {
8 const { isLoggedIn, setUser } = useContext(MyContext)
9 const router = useRouter()
10
11 let [username, setUsername] = useState("");
12 let [email, setEmail] = useState("");
13 let [password, setPassword] = useState("")
14 const [loading, setLoading] = useState(false);
15 const [errors, setErrors] = useState({});
16 useEffect( () => {
17 if (isLoggedIn) {
18 return router.push("/dashboard");
19 }
20 }, [isLoggedIn])
21 const submit = async () => {
22 if(!username.trim()) return setErrors({ username: "Username must not be empty"})
23 if(!email) return setErrors({ email: "Email must not be empty"})
24 if(!password) return setErrors({ password: "Password must not be empty"})
25
26 setLoading(true);
27 const reg = await (register(username, email, password))
28 setLoading(false);
29 if(reg.jwt){
30 setUser(reg.user);
31 router.push('/dashboard')
32 }else{
33 setErrors({ server: reg?.error?.message || 'Error from server' });
34 }
35 }
36 return (
37 <div className="flex flex-col items-center justify-center min-h-screen py-2">
38 <Head>
39 <title>Create Next App</title>
40 <link rel="icon" href="/favicon.ico" />
41 </Head>
42 <main className="flex flex-col items-center justify-center w-full flex-1 px-20 text-center">
43 <h1 className="text-6xl font-bold text-blue-600">
44 Url Shortener
45 </h1>
46
47 <div className="flex flex-wrap items-center justify-around max-w-4xl mt-6 sm:w-full">
48 <form className="w-full max-w-lg mt-8" onSubmit={(e) => { e.preventDefault(); submit() }}>
49 <div className="flex flex-wrap -mx-3 mb-2">
50 <div className="w-full px-3 mb-6 md:mb-0">
51 <input onChange={ (e) => setUsername(e.target.value)} placeholder="Enter username" className={`appearance-none block w-full text-gray-700 mb-4 border rounded py-3 px-4 leading-tight focus:outline-none focus:bg-white focus:border-gray-500 ${errors.username ? "border-red-500" : "border-gray-200"}`} id="grid-username" type="text" />
52 {errors.username ? (
53 <p className="text-red-500 text-xs italic">{errors.username}</p>
54 ) : ''}
55 </div>
56 </div>
57 <div className="flex flex-wrap -mx-3 mb-2">
58 <div className="w-full px-3 mb-6 md:mb-0">
59 <input onChange={ (e) => setEmail(e.target.value)} placeholder="Enter email" className={`appearance-none block w-full text-gray-700 mb-4 border rounded py-3 px-4 leading-tight focus:outline-none focus:bg-white focus:border-gray-500 ${errors.email ? "border-red-500" : "border-gray-200"}`} id="grid-email" type="email" />
60 {errors.email ? (
61 <p className="text-red-500 text-xs italic">{errors.email}</p>
62 ) : ''}
63 </div>
64 </div>
65 <div className="flex flex-wrap -mx-3 mb-6">
66 <div className="w-full px-3">
67 <span className={`w-full inline-flex items-center rounded border border-r-1 text-gray-700 mb-2 text-sm focus:outline-none focus:bg-white focus:border-gray-500 ${errors.password ? "border-red-500 " : " border-gray-200"}`}>
68 <input onChange={ (e) => setPassword(e.target.value)} placeholder="******************" className="appearance-none block rounded w-full py-3 px-4 leading-tight" id="grid-password" type='password' />
69 </span>
70 {errors.password ? (
71 <p className="text-red-500 text-xs italic">{errors.password}</p>
72 ) : ''}
73 </div>
74 </div>
75 {errors.server ? (
76 <p className="text-red-500 text-xs italic">{errors.server}</p>
77 ) : ''}
78 <div className="flex flex-row flex-wrap justify-between">
79
80 <span className="text-blue-600 hover:text-gray-600 pt-2 md:p-6"> <Link href="/login">Back to Login?</Link></span>
81 <button disabled={loading} className={`w-full md:w-1/2 mt-3 flex justify-center hover:bg-gray-200 hover:text-gray-900 rounded-md px-3 py-3 uppercase ${loading ? "bg-gray-200 text-black cursor-not-allowed" : "bg-gray-900 text-white cursor-pointer"}`}>
82 {loading ? (
83 <>
84 loading ...
85 </>
86 ) : 'Register'}
87 </button>
88 </div>
89 </form>
90 </div>
91 </main>
92 </div>
93 )
94 }
The above code registers users to the platform, allowing us to create a secured page later for people to come in, create, manage and track their shortened URLs.
We also use the useContext
hook to get our state values and functions:
1 import React, { useState, useContext, useEffect } from 'react';
2 import MyContext from '../lib/context';
3 const { isLoggedIn, setUser } = useContext(MyContext)
Also, we use the useEffect
hook to apply middleware on the page, so that only the unauthenticated user can access the page. We achieve this using the isLoggedIn
state:
1 import React, { useState, useContext, useEffect } from 'react';
2 useEffect( () => {
3 if (isLoggedIn) {
4 return router.push("/dashboard");
5 }
6 }, [isLoggedIn])
If a user is authenticated, we redirect them back to their dashboard.
The submit
method handles user registration, validates and sets the user
state to the signed user if successful and then redirects the user to their dashboard:
1 const submit = async () => {
2 if(!username.trim()) return setErrors({ username: "Username must not be empty"})
3 if(!email) return setErrors({ email: "Email must not be empty"})
4 if(!password) return setErrors({ password: "Password must not be empty"})
5
6 setLoading(true);
7 const reg = await (register(username, email, password))
8 setLoading(false);
9 if (reg.jwt) {
10 setUser(reg.user);
11 router.push('/dashboard')
12 } else{
13 setErrors({ server: reg?.error?.message || 'Error from server' });
14 }
15 }
As can be seen, we make use of a function called register
, which handles the sending of a request to the Strapi API:
1import { register } from '../lib/auth'
2const reg = await register(username, email, password)
We proceed to create this file (auth.js
) in the lib
folder. This file makes authenticated requests to our API and handles other auth-related functions like logout. Add the content below into the file:
1 import Cookie from "js-cookie";
2 const API_URL = process.env.NEXT_PUBLIC_API_URL || "http://localhost:1337";
3
4 export const register = async (username, email, password) => {
5 try {
6 let response = await fetch(`${API_URL}/api/auth/local/register`, {
7 method: 'POST',
8 body: JSON.stringify({ username, email, password }),
9 headers: {
10 'Content-Type': 'application/json'
11 },
12 });
13 response = await response.json();
14 if (response) {
15 Cookie.set("jwt", response.jwt);
16 }
17 return response
18 } catch (e) {
19 return { error: 'An error occured' }
20 }
21
22 };
23 export const login = async (identifier, password) => {
24 try {
25 let response = await fetch(`${API_URL}/api/auth/local`, {
26 method: 'POST',
27 body: JSON.stringify({ identifier, password }),
28 headers: {
29 'Content-Type': 'application/json'
30 },
31 });
32 response = await response.json();
33 if (response) {
34 Cookie.set("jwt", response.jwt);
35 }
36 return response
37 } catch (e) {
38 return { error: 'An error occured' }
39 }
40
41 };
42 export const logout = () => {
43 Cookie.remove("jwt");
44 };
As can be seen, we use the js-cookie
package to assign the jwt
once a user is logged in or registered, as well as delete this token once the user logs out.
This also leads us to create a .env
at the root of our project. Inside it, we would have:
1 NEXT_PUBLIC_API_URL=http://localhost:1337
Now, we would go on to create the Login file. Add the content below to the newly create pages/login.js
file:
1 import Head from 'next/head'
2 import React, { useState, useEffect, useContext } from 'react';
3 import MyContext from '../lib/context';
4 import { useRouter } from "next/router";
5 import { login } from '../lib/auth'
6 import Link from 'next/link'
7 export default function Login() {
8
9 let [email, setEmail] = useState("");
10 let [password, setPassword] = useState("")
11 const [loading, setLoading] = useState(false);
12 const [errors, setErrors] = useState({});
13 const { isLoggedIn, setUser } = useContext(MyContext)
14 const router = useRouter()
15 const signIn = async () => {
16 if(!email) return setErrors({ email: "Email must not be empty"})
17 if(!password) return setErrors({ password: "Password must not be empty"})
18
19 setLoading(true);
20 const reg = await (login(email, password))
21 setLoading(false);
22 if(reg.jwt){
23 setUser(reg.user);
24 router.push('/')
25 }else{
26 setErrors({ server: reg?.error?.message || 'Error from server' });
27 }
28 }
29 useEffect( () => {
30 if (isLoggedIn) {
31 return router.push("/dashboard");
32 }
33 }, [isLoggedIn])
34
35 return (
36 <div className="flex flex-col items-center justify-center min-h-screen py-2">
37 <Head>
38 <title>Create Next App</title>
39 <link rel="icon" href="/favicon.ico" />
40 </Head>
41 <main className="flex flex-col items-center justify-center w-full flex-1 px-20 text-center">
42 <h1 className="text-6xl font-bold text-blue-600">
43 Url Shortener
44 </h1>
45
46 <div className="flex flex-wrap items-center justify-around max-w-4xl mt-6 sm:w-full">
47 <form className="w-full max-w-lg mt-8" onSubmit={(e) => { e.preventDefault(); signIn(email, password) }}>
48 <div className="flex flex-wrap -mx-3 mb-2">
49 <div className="w-full px-3 mb-6 md:mb-0">
50 <input onChange={ (e) => setEmail(e.target.value)} placeholder="Enter email..." className={`appearance-none block w-full text-gray-700 mb-4 border rounded py-3 px-4 leading-tight focus:outline-none focus:bg-white focus:border-gray-500 ${errors.email ? "border-red-500" : "border-gray-200"}`} id="grid-email" type="email" />
51 {errors.email ? (
52 <p className="text-red-500 text-xs italic">{errors.email}</p>
53 ) : ''}
54 </div>
55 </div>
56 <div className="flex flex-wrap -mx-3 mb-6">
57 <div className="w-full px-3">
58 <span className={`w-full inline-flex items-center rounded border border-r-1 text-gray-700 mb-2 text-sm focus:outline-none focus:bg-white focus:border-gray-500 ${errors.password ? "border-red-500 " : " border-gray-200"}`}>
59 <input onChange={ (e) => setPassword(e.target.value)} placeholder="******************" className="appearance-none block rounded w-full py-3 px-4 leading-tight" id="grid-password" type='password' />
60 </span>
61 {errors.password ? (
62 <p className="text-red-500 text-xs italic">{errors.password}</p>
63 ) : ''}
64 </div>
65 </div>
66 {errors.server ? (
67 <p className="text-red-500 text-xs italic">{errors.server}</p>
68 ) : ''}
69 <div className="flex flex-row flex-wrap justify-between">
70 <button disabled={loading} className={`w-full md:w-1/2 mt-3 flex justify-center align-center hover:bg-gray-200 hover:text-gray-900 rounded-md px-2 py-3 uppercase ${loading ? "bg-gray-200 text-black cursor-not-allowed" : "bg-gray-900 text-white cursor-pointer"}`}>
71 {loading ? (
72 <>
73 loading ...
74 </>
75 ) : 'LOG IN'}
76 </button>
77 <span className="text-blue-600 hover:text-gray-600 pt-2 md:p-6"> <Link href="/register">Register</Link></span>
78 </div>
79 </form>
80 </div>
81 </main>
82
83 </div>
84 )
85 }
The above code allows users to login and get access to the secured dashboard. It is similar to the register, only that it doesn't create users but checks their existence in the record and authenticates them.
This also makes use of the lib/auth.js
file which we have seen already.
The remaining pages we would be looking at now are the:
As discussed earlier, this page shows all created records, as well as enables the user to test them and delete them.
Proceed to create a file called dashboard.js
in the pages folder pages/dashboard.js
. Insert the code below as its content:
1 import Head from 'next/head'
2 import React, { useEffect, useContext, useState } from 'react';
3 import MyContext from '../lib/context';
4 import { useRouter } from "next/router";
5 import Link from 'next/link';
6 import { logout } from '../lib/auth'
7 import { get, deleteAlias } from '../lib/shortener'
8
9 export default function Dashboard() {
10 const { isLoggedIn, setUser, user, setUrls, urls } = useContext(MyContext)
11 const router = useRouter()
12 const getAll = async () => {
13 let short = await get()
14 if (!short) return
15 setUrls(short?.data?.attributes?.results || null)
16 }
17 const deleteShort = async (id) => {
18 if (!id) return
19 let deleted = await deleteAlias(id)
20 if (deleted.data && !deleted.error) {
21 await getAll()
22 }
23 }
24 useEffect(() => {
25 if (!isLoggedIn) {
26 return router.push("/login");
27 }
28 getAll()
29 }, [urls.length])
30
31 const signOut = () => {
32 logout()
33 setUser(null)
34 router.push('/login')
35 }
36
37 return (
38 <div className="flex flex-col items-center justify-center min-h-screen py-2">
39 <Head>
40 <title>Dashboard</title>
41 <link rel="icon" href="/favicon.ico" />
42 </Head>
43 <header className="flex justify-between align-center p-4 h-32 w-full text-6xl font-bold text-blue-600">
44 <h1 className="text-6xl font-bold text-blue-600">
45 Url Shortener
46 </h1>
47 <span className="text-sm font-bold text-red-600 cursor-pointer" onClick={() => signOut()}>Logout</span>
48 </header>
49 <main className="flex flex-col items-center w-full mt-0 flex-1 px-8 text-center">
50
51 <p className="flex flex-wrap w-full text-lg font-bold">
52 Welcome {user?.username || ""}
53 </p>
54 <div className="flex flex-wrap items-center justify-around max-w-4xl mt-6 sm:w-full">
55 <div className="shadow border-b w-full overflow-hidden border-gray-200 sm:rounded-lg">
56 <table className="min-w-full divide-y divide-gray-200">
57 <thead>
58 <tr>
59 <th scope="col" className="px-6 py-3 bg-gray-50 text-center text-xs font-medium text-gray-500 uppercase tracking-wider">
60 Url
61 </th>
62 <th scope="col" className="px-6 py-3 bg-gray-50 text-center text-xs font-medium text-gray-500 uppercase tracking-wider">
63 Alias/Shortned
64 </th>
65 <th scope="col" className="px-6 py-3 bg-gray-50 text-center text-xs font-medium text-gray-500 uppercase tracking-wider">
66 No of hits
67 </th>
68 <th scope="col" className="px-6 py-3 bg-gray-50">
69 <span className="sr-only">Remove</span>
70 </th>
71 </tr>
72 </thead>
73 <tbody className="bg-white divide-y divide-gray-200">
74 {(!urls || urls.length == 0) && (
75 <tr>
76 <td colSpan="3" className="px-2 py-4 whitespace-nowrap cursor-pointer">
77 No record found
78 </td>
79 </tr>
80 )}
81 {urls && urls.map(short =>
82 (
83 <tr className="hover:bg-gray-200" key={short.id}>
84 <td className="px-2 py-4 whitespace-nowrap cursor-pointer" title = "Open Url" onClick={() => { window.open(`${short.url}`, 'blank') }}>
85 <div className="text-sm text-gray-900">{short?.url || 'N/A'}</div>
86 </td>
87 <td className="px-2 py-4 whitespace-nowrap cursor-pointer" title = "Test Alias" onClick={() => { window.open(`/${short.alias}`, 'blank') }}>
88 <div className="text-sm text-gray-900">{short?.alias || 'N/A'}</div>
89 </td>
90 <td className="px-2 py-4 whitespace-nowrap cursor-pointer">
91 <span className="px-2 text-xs leading-5 font-semibold rounded-full ">
92 <div className="text-sm text-gray-500">
93 {short?.visit || 0}
94 </div>
95 </span>
96 </td>
97 <td className="px-2 py-2 whitespace-nowrap text-center text-sm font-medium">
98 <button onClick={() => deleteShort(short.id)} className="text-red-600 hover:text-red-900 mx-1">Delete</button>
99 </td>
100 </tr>
101 )
102 )}
103 </tbody>
104 </table>
105 </div>
106 </div>
107 </main>
108 <Link href="/addUrl">
109 <button className="absolute rounded-full text-white font-bold text-lg p-2 bg-blue-800 w-12 h-12 m-4 right-0 bottom-0 hover:bg-blue-400"> + </button>
110 </Link>
111 </div>
112 )
113 }
In a nutshell, we use this to show users their shortened URLs. As can be seen, we use the useEffect
hook to help prevent unauthenticated users from accessing the page.
Also, we have functions to handle deleting a record, getting all records, and logout users.
The functions that handle the delete
and get
, call a central shortener helper file called shortener.js
:
1 import { get, deleteAlias } from '../lib/shortener'
We use this file to handle all shortener related functionalities. Hence, we proceed to create this file inside the lib folder, lib/shortener.js
, and add the code below as its content:
1 import Cookie from "js-cookie";
2 const API_URL = process.env.NEXT_PUBLIC_API_URL || "http://localhost:1337";
3
4 export const get = async () => {
5 const token = Cookie.get("jwt");
6 try {
7 let response = await fetch(`${API_URL}/api/shortners`, {
8 method: 'GET',
9 headers: {
10 'Content-Type': 'application/json',
11 'Authorization': `Bearer ${token}`
12 },
13 });
14 response = await response.json();
15 return response
16 } catch (e) {
17 return { error: 'An error occured' }
18 }
19 };
20
21 export const getSingle = async (alias) => {
22 try {
23 let response = await fetch(`${API_URL}/api/shortners?alias=${alias}`, {
24 method: 'GET',
25 headers: {
26 'Content-Type': 'application/json'
27 },
28 });
29 response = await response.json();
30 return response
31 } catch (e) {
32 return { error: 'An error occured' }
33 }
34 }
35
36 export const create = async (url, alias) => {
37 const token = Cookie.get("jwt");
38 try {
39 let response = await fetch(`${API_URL}/api/shortners`, {
40 method: 'POST',
41 body: JSON.stringify({ data: { url, alias } }),
42 headers: {
43 'Content-Type': 'application/json',
44 'Authorization': `Bearer ${token}`
45 },
46 });
47 response = await response.json();
48 return response
49 } catch (e) {
50 return { error: 'An error occured' }
51 }
52 };
53
54 export const deleteAlias = async (id) => {
55 const token = Cookie.get("jwt");
56
57 try {
58 let response = await fetch(`${API_URL}/api/shortners/${id}`, {
59 method: 'DELETE',
60 headers: {
61 'Content-Type': 'application/json',
62 'Authorization': `Bearer ${token}`
63 },
64 });
65
66 response = await response.json();
67 return response
68 } catch (e) {
69 return { error: 'An error occured' }
70 }
71 };
As discussed earlier, this page handles the creation of shortened URLs. Proceed to create a file called addUrl.js
inside the pages folder, pages/addUrl.js
.
Next, add the content below as its new content:
1 import Head from 'next/head';
2 import Link from 'next/link';
3 import React, { useEffect, useContext, useState } from 'react';
4 import MyContext from '../lib/context';
5 import { useRouter } from "next/router";
6 import { logout } from '../lib/auth';
7 import { create } from '../lib/shortener';
8
9 export default function AddUrl() {
10 const { isLoggedIn, setUser } = useContext(MyContext)
11 const [url, setUrl] = useState("");
12 const [alias, setAlias] = useState("");
13 const [loading, setLoading] = useState(false);
14 const [errors, setErrors] = useState({});
15 const router = useRouter();
16 useEffect(() => {
17 if (!isLoggedIn) {
18 return router.push("/login");
19 }
20 }, [isLoggedIn]);
21 const shorten = async () => {
22 if (!url) return setErrors({ url: "Url must not be empty" })
23 if (!alias) return setErrors({ alias: "Alias must not be empty" })
24 setLoading(true);
25 const short = await(create(url, alias))
26 setLoading(false);
27 if (short.data && !short.error) {
28 router.push('/dashboard')
29 } else {
30 setErrors({ server: short?.error?.message || 'Error from server' });
31 }
32 }
33 const signOut = () => {
34 logout();
35 setUser(null);
36 router.push('/login');
37 }
38 return (
39 <div className="flex flex-col items-center justify-center min-h-screen py-2">
40 <Head>
41 <title>Add Url</title>
42 <link rel="icon" href="/favicon.ico" />
43 </Head>
44 <header className="flex justify-between align-center p-4 h-32 w-full text-6xl font-bold text-blue-600">
45 <h1 className="text-6xl font-bold text-blue-600">
46 Url Shortener
47 </h1>
48 <span className="text-sm font-bold text-red-600 cursor-pointer" onClick={() => signOut()}>Logout</span>
49 </header>
50 <main className="flex flex-col items-center w-full mt-0 flex-1 px-8 text-center">
51
52 <p className="flex flex-wrap w-full text-lg font-bold">
53 Fill the form
54 </p>
55 <div className="flex flex-wrap items-center justify-around max-w-4xl mt-6 sm:w-full">
56 <form className="w-full max-w-lg mt-8" onSubmit={(e) => { e.preventDefault(); shorten() }}>
57 <div className="flex flex-wrap -mx-3 mb-2">
58 <div className="w-full px-3 mb-6 md:mb-0">
59 <input onChange={(e) => setUrl(e.target.value)} placeholder="Enter url" className={`appearance-none block w-full text-gray-700 mb-4 border rounded py-3 px-4 leading-tight focus:outline-none focus:bg-white focus:border-gray-500 ${errors.url ? "border-red-500" : "border-gray-200"}`} id="grid-url" type="text" />
60 {errors.url ? (
61 <p className="text-red-500 text-xs italic">{errors.url}</p>
62 ) : ''}
63 </div>
64 </div>
65 <div className="flex flex-wrap -mx-3 mb-2">
66 <div className="w-full px-3 mb-6 md:mb-0">
67 <input onChange={(e) => setAlias(e.target.value)} placeholder="Enter alias" className={`appearance-none block w-full text-gray-700 mb-4 border rounded py-3 px-4 leading-tight focus:outline-none focus:bg-white focus:border-gray-500 ${errors.alias ? "border-red-500" : "border-gray-200"}`} id="grid-alias" type="text" />
68 {errors.alias ? (
69 <p className="text-red-500 text-xs italic">{errors.alias}</p>
70 ) : ''}
71 </div>
72 </div>
73 {errors.server ? (
74 <p className="text-red-500 text-xs italic">{errors.server}</p>
75 ) : ''}
76 <div className="flex flex-row flex-wrap justify-between">
77 <span className="text-blue-600 hover:text-gray-600 pt-2 md:p-6"> <Link href="/dashboard"> Back to Dashboard</Link></span>
78 <button disabled={loading} className={`w-full md:w-1/2 mt-3 flex justify-center hover:bg-gray-200 hover:text-gray-900 rounded-md px-3 py-3 uppercase ${loading ? "bg-gray-200 text-black cursor-not-allowed" : "bg-gray-900 text-white cursor-pointer"}`}>
79 {loading ? (
80 <>
81 loading ...
82 </>
83 ) : 'Shorten'}
84 </button>
85 </div>
86 </form>
87 </div>
88 </main>
89 </div>
90 )
91 }
This is quite straightforward to understand, we simply make use of the shortener file in the lib
folder to make a request to our Strapi API to add the record.
We also make use of the useEffect
hook to prevent unauthenticated users from accessing the page.
This page is the one which is in charge of checking if the alias exists in our record and redirecting the user accordingly.
Subsequently, if an alias is found in our record, the Strapi API records that as a visit to the alia, giving us the ability to see analytics ofa particular alias.
We proceed to create a file called [alias].js
in the pages folder, pages/[alias].js
. If this looks strange, check how to build pages with dynamic routes in the Next.js.
Next, insert the content below as the content of this file:
1 import { useRouter } from "next/router";
2 import { useEffect } from "react";
3 import { getSingle } from "../lib/shortener";
4
5 const AliasView = ({ error }) => {
6 const router = useRouter()
7 useEffect(() => {
8 if (error) {
9 return router.push('/')
10 }
11 }, [])
12 return null
13 };
14
15 export async function getServerSideProps({ params }) {
16 const url = await getSingle(params.alias)
17 if (url.data && (url.data?.attributes?.results[0] || false) && !url.error) {
18 return {
19 redirect: {
20 destination: url.data.attributes.results[0].url,
21 permanent: false,
22 },
23 }
24 }
25 return {
26 props: { error: "error" }
27 }
28 }
29
30 export default AliasView;
As can be seen, we use the getServerSideProps
to check if the alias exists in our record, if so we redirect to the actual URL.
1 export async function getServerSideProps({ params }) {
2 const url = await getSingle(params.alias)
3 if (url.data && (url.data?.attributes?.results[0] || false) && !url.error) {
4 return {
5 redirect: {
6 destination: url.data.attributes.results[0].url,
7 permanent: false,
8 },
9 }
10 }
11 return {
12 props: { error: "error" }
13 }
14 }
15
16If we can’t find it, we pass the `error` prop to the actual component:
17
18
19 return {
20 props: { error: "error" }
21 }
22
23Then in our component, we redirect the user to the home page since the alias isn't in our record.
24
25
26 const AliasView = ({ error }) => {
27 const router = useRouter()
28 useEffect(() => {
29 if (error) {
30 return router.push('/')
31 }
32 }, [])
33 return null
34 };
If the user is authenticated, they would get redirected to the Dashboard
page, else they would get redirected to the Login
page. Did we implement this feature on the Index.js page? Yes, we did!
And that's it for the code section of the frontend part of this tutorial. If you have come this far, I must say you are doing great!
Enough for all this technical stuff, in the next section, we would be seeing a demo of the finished app.
The finished app looks like this:
https://www.youtube.com/watch?v=T7e_A6bUejM
The benefits a URL Shortener brings can’t be over-emphasized. This is seen in the rapid outbreak of companies playing in this space. You can go ahead to add more features to this project, by simply forking the repo (found at beginning of this tutorial) and getting your hands dirty. It's best left to the imagination what you can achieve!
This tutorial demonstrated how easily you can build a URL Shortener Service in about 20 minutes using technologies like Next.js and Strapi. Once again, Strapi has shown us that it is equal to the task when it comes to creating great APIs!
A full-stack developer, technical writer, and lover of Jamstack, passionate about lifelong learning, open and inclusive communities, and a big advocate of open source.