Build a URL shortener for marketing content analytics
Tags: appwrite, javascript, tutorial, cloud
Published: 2024-01-15 10:05:34

In a world saturated with content across various platforms, understanding the effectiveness of created content is paramount. Marketing content analytics provides a lens through which businesses can evaluate the impact of their strategies, ensuring they resonate with the target audience.

A vital element of content analytics is the URL shortener, which focuses on aesthetics and user experience and enables marketers to create shorter and trackable links. By condensing lengthy URLs into compact forms, these tools streamline the presentation of links in various channels, including social media, emails, and print materials. 

This post discusses building a URL shortener to maximize content analytics using [Remix](https://remix.run/?utm_source=hackmamba&utm_medium=hackmamba-blog) and [Appwrite’s](https://appwrite.io/?utm_source=hackmamba&utm_medium=hackmamba-blog) Function Template — URL Shortener.

The complete source code can be found on **GitHub**. Clone and fork it to get started!
{% embed https://github.com/ugwutotheeshoes/remix-url-shortener %}


###Prerequisites

To comfortably follow along in this article, you’ll need the following:

- A basic understanding of [Remix](https://remix.run/?utm_source=hackmamba&utm_medium=hackmamba-blog).
- A GitHub account. Create one [here](https://github.com/signup).
- Appwrite Cloud [account](https://cloud.appwrite.io/register?utm_source=hackmamba&utm_medium=hackmamba-blog). 

#Getting started
###Setting up an Appwrite project

Appwrite Functions are a powerful tool that allows developers to extend their applications’ capabilities in a few simple steps. We’ll first need to create a project on Appwrite’s console to get started. To do this, log into the Appwrite console, click the **Create project** button, name the project `appwrite-url-shortener` , and click **Create**.

![Name the project](https://paper-attachments.dropboxusercontent.com/s_389E16C510B8C09FE137F1FB088E286D9AEF1197F5E224B2D125DF96F0B9D05C_1701719139993_Organizations-Appwrite+6.png)

###Create a function

Here, we’ll create an Appwrite function to condense lengthy URLs. Let’s navigate to the **Functions** tab on the sidebar and click **Create Function** to create a new function.

![Create function](https://paper-attachments.dropboxusercontent.com/s_389E16C510B8C09FE137F1FB088E286D9AEF1197F5E224B2D125DF96F0B9D05C_1701720258652_Functions-Appwrite+13.png)


Next, click the GitHub button since we’ll manage our functions in a GitHub repository. To give Appwrite access to all repositories in the GitHub account, select **All repositories** and then click **Install and Authorize**.


![Install and authorize GitHub](https://paper-attachments.dropboxusercontent.com/s_2D5BFB394AE5FDCC7761790C9993D914C35D18A2D85912F49728BE3408944623_1697750676519_Functions-Appwrite+3.png)


Click on **All templates** and search **Url Shortener**, then click on **Create function** to set up the function.


![Select all templates](https://paper-attachments.dropboxusercontent.com/s_2D5BFB394AE5FDCC7761790C9993D914C35D18A2D85912F49728BE3408944623_1697576089539_Functions-Appwrite+1.png)
![Search and select the “Url Shortener” template](https://paper-attachments.dropboxusercontent.com/s_389E16C510B8C09FE137F1FB088E286D9AEF1197F5E224B2D125DF96F0B9D05C_1704324855308_image.png)


Here, we’ll configure the template using the details below. Name the template **URL shortener**, then select any **Node.js runtime** from the dropdown list. Click on **Next**.

![Set configurations](https://paper-attachments.dropboxusercontent.com/s_389E16C510B8C09FE137F1FB088E286D9AEF1197F5E224B2D125DF96F0B9D05C_1701725780706_Functions-Appwrite+15.png)


In this section, we’ll need to set the environmental variables as shown below.

- `APPWRITE_API_KEY`: This API key lets us interact with the Appwrite server APIs. It is generated once the function is created and can be obtained from the **Setting** tab on the project's dashboard. Tick the **Generate API key** box since we want to generate a key on completion.


- `SHORT_BASE_URL`: This is a domain to use for the short URLs. The functions subdomain or a custom domain are viable options here. Let’s use a sample value — https://short.app/s. We’ll reconfigure this to the function’s subdomain once the function fully initializes. You can eventually swap this with your custom subdomain.


- Optional variables: Leave this as it is. We’ll replace the `APPWRITE_DATABASE_ID` and `APPWRITE_COLLECTION_ID` later on once we create a database to store the lengthy URLs.

After applying the configurations above, click **Next**.


![Set the environment variables](https://paper-attachments.dropboxusercontent.com/s_389E16C510B8C09FE137F1FB088E286D9AEF1197F5E224B2D125DF96F0B9D05C_1703084866828_image.png)


Next, select the **Create a new repository** option and click **Next**. Then, input url-shortener as the repository’s name and click **Next**.

![Connect the function template to a repository](https://paper-attachments.dropboxusercontent.com/s_2D5BFB394AE5FDCC7761790C9993D914C35D18A2D85912F49728BE3408944623_1699388640200_Functions-Appwrite+11.png)
![Name the repository](https://paper-attachments.dropboxusercontent.com/s_389E16C510B8C09FE137F1FB088E286D9AEF1197F5E224B2D125DF96F0B9D05C_1701727734204_Functions-Appwrite+17.png)


After naming the repo, select the existing repository's default branch, then click **Create**. This exports the function template into a suitable directory in the repository.

![Select the default branch](https://paper-attachments.dropboxusercontent.com/s_389E16C510B8C09FE137F1FB088E286D9AEF1197F5E224B2D125DF96F0B9D05C_1701727826550_Functions-Appwrite+18.png)


After this, our function template is successfully created and deployed. We should see the deployed source code in our GitHub repository.

![Deployed template console](https://paper-attachments.dropboxusercontent.com/s_389E16C510B8C09FE137F1FB088E286D9AEF1197F5E224B2D125DF96F0B9D05C_1703085238291_yaba.png)
![Deployed template on GitHub](https://paper-attachments.dropboxusercontent.com/s_389E16C510B8C09FE137F1FB088E286D9AEF1197F5E224B2D125DF96F0B9D05C_1703094925872_WxdSJHRg.png)


Next, let’s copy the **Domain** link on the deployed template console, head to the **Setting** tab, and reconfigure the `SHORT_BASE_URL` variable using the function subdomain link.

![Copy the domain link](https://paper-attachments.dropboxusercontent.com/s_389E16C510B8C09FE137F1FB088E286D9AEF1197F5E224B2D125DF96F0B9D05C_1703085576980_sHZ2ajlg.png)
![Replace the variable](https://paper-attachments.dropboxusercontent.com/s_389E16C510B8C09FE137F1FB088E286D9AEF1197F5E224B2D125DF96F0B9D05C_1701728083296_Functions-Appwrite+19.png)

###Creating a Database, Collection, and Attribute

Next, we’ll create a database to store and replace a lengthy URL with a shorter one. On the left side of the Appwrite Console dashboard, click on the **Database** tab. Click on the **Create Database** button to create a new database. Creating a new database will lead us to the **Collection** page.

![Create a database](https://paper-attachments.dropboxusercontent.com/s_389E16C510B8C09FE137F1FB088E286D9AEF1197F5E224B2D125DF96F0B9D05C_1701719245061_Databases-Appwrite+5.png)
![Database name](https://paper-attachments.dropboxusercontent.com/s_389E16C510B8C09FE137F1FB088E286D9AEF1197F5E224B2D125DF96F0B9D05C_1701719327368_Databases-Appwrite+6.png)


Next, we’ll create a collection in our database by clicking the **Add Collection** button.


![Create a collection](https://paper-attachments.dropboxusercontent.com/s_389E16C510B8C09FE137F1FB088E286D9AEF1197F5E224B2D125DF96F0B9D05C_1701719812999_Database-Appwrite+6.png)


Afterward, head to the **Attribute** tab and click the **Create Attribute** button. Then, select the **String** option from the dropdown menu. Fill in **url** as the **Attribute name**, put **1000** as the **Attribute Size**, and then click the **Create** button.

Copy the **Database** and **Collection ID** on the Collection dashboard, then head back to the **Url-shortener** template. Here, replace the `APPWRITE_DATABASE_ID` and `APPWRITE_COLLECTION_ID` variables we got earlier.

##Project setup and installation

We’ll use Remix.js to handle the frontend component.

Run the following command in the terminal as shown below:

```js
npx create-remix@latest --template  https://github.com/ugwutotheeshoes/remix-js
```

The command above clones a Remix application with a JavaScript template. 
To use Appwrite in your Remix application, install the Appwrite client-side SDK for web applications.

```js
npm install appwrite
```

Then, navigate into the project directory `cd <project-name>` and run `npm run dev` to start a development server at https://localhost:3000/ in your browser.


> **NOTE**: We’re using a Remix.js template since this article is JavaScript-based. However, Typescript is also applicable.

#Building the app’s functionality

To build the app’s functionality, head to the `app/routes/index.jsx` file and add the code snippet below. 

```js
    // index.jsx
    export default function Index() {  
      const [show, setShow] = useState(false);
      const [longUrl, setLongUrl] = useState("");
      const [shortUrl, setShortUrl] = useState("");
    
    const client = new Client();
        .setEndpoint("OUR_API_ENDPOINT") // Your API Endpoint
        .setProject("OUR_PROJECT_ID"); // Your project ID
     const functions = new Functions(client);
      
    
      const handleChange = (e) => {
         e.preventDefault();
         setLongUrl(e.target.value );
      };
    
      const handleSubmit = () => {
        const execution = functions.createExecution(
          "OUR_FUNCTION_ID", JSON.stringify({ url: longUrl, }), false, "/", "POST",
          {
            "Content-Type": "application/json",
          }
        );
        execution.then(
          function (response) {
            setShortUrl(response.responseBody);
            setShow(true);
            setLongUrl("");
            console.log(response);
          },
          function (error) {
            console.log(error); // Failure
          }
        );
      };
    return (
     <div className="container">
          <form onSubmit={handleSubmit}>
            <label>Paste your URL here:</label>
            <div className="section">
              <input
                type="text"
                placeholder="URL"
                value={longUrl}
                onChange={handleChange}
              />
              <button type="submit">Submit</button>
            </div>
          </form>
          {show && (
            <p>
              <span>Here's your short link:</span>
              {shortUrl}
            </p>
          )}
        </div>
      )
    }
```

The snippet above does the following:

- Creates a form and some variables to store a URL.
- Imports the required dependencies to interact with Appwrite servers.
- Creates a request to Appwrite to store the lengthy URL as a new document in the Database we created earlier. For that, we’ll use the **Database** and **Collection ID** here.
- Stores the created Document’s ID from the response.
- Displays the new shortened link, which comprises the function’s subdomain and the Document ID.
Demo

The app should function like this after applying the necessary configurations above:
{% embed https://www.loom.com/share/2c65eeae70f74c9789d11e879f35faf4?sid=94613255-82f0-457b-87ec-c114867137cd %}


#Conclusion

This post highlights the integration of the Appwrite Function template URL shortener in a Remix application. This template can significantly simplify content analysis, providing aesthetic benefits and, more importantly, a reliable means to assess and enhance the efficiency of content distribution across diverse digital platforms.

#Resources

These resources may also be helpful:

- [Remix Documentation](https://remix.run/docs/en/1.19.3?utm_source=hackmamba&utm_medium=hackmamba-blog)
- [Appwrite Cloud Function Guide](https://appwrite.io/docs/references/cloud/client-web/functions?utm_source=hackmamba&utm_medium=hackmamba-blog)
- [Appwrite Cloud Function Development](https://appwrite.io/docs/products/functions/development?utm_source=hackmamba&utm_medium=hackmamba-blog)