Generating Link Previews with React and Nodejs

Link previews are a common feature of all major apps, especially social media applications and other applications that allow users to post their own content.
They are important in many ways:

  • It allows users to know the kind of content on the website a URL points to.

  • It provides a sneak peek and this increases the chances of a user clicking on a link.

  • It also provides a good user experience.

The aim of this series is for us to build a simple application to generate link previews. This application comes with two different parts; a backend to do the actual preview generation and a frontend to render the data.

Part 1.

In this part we are going to build out the backend, I will assume at least some basic knowledge of Node and Expressjs though. Let's get started then.

First, create a folder called preview_api and open it in your terminal. You should have something like the screenshot below in your terminal.

Now let's initialise a new Nodejs project.

npm init

After this, follow the prompts and provide the needed information. You should have something like the screenshot below when done.

Now let's start coding.

code .

Run this command to open your project in Vscode. You should have something like the screenshot below on your desktop.

Let's add a "type": "module" field to our package.json, this allows us to use ESModule syntax i.e. import and export instead of require. Reference the screenshot below.

Now let's create our root file, let's call it index.js. This is going to have all the code for our API.

Now install some dependencies;

  • Cheerio - Cheerio is a popular package that allows you to parse and manipulate HTML or XML documents using a simple and intuitive syntax similar to jQuery. It provides a fast and efficient way to traverse the HTML DOM (Document Object Model) and extract data from web pages. With Cheerio, you can easily scrape web pages, extract specific elements, modify HTML structures, and much more.

  • Axios - Axios is a popular package for making HTTP requests from a Node.js application. It provides a simple and elegant API for sending HTTP requests to various endpoints and processing the responses.

  • Express - Express is a popular web application framework for Node.js that provides a robust set of features for building web applications and APIs. It provides a minimalistic and flexible approach to building web applications, allowing developers to create powerful web services with minimal overhead.

npm install express axios cheerio

Let's set up our API with express. Type the code below into index.js.

import express from "express";

//initialise express application
const app = express();

//tell express to expose server from port 3000
app.listen(3000, () => {
  console.log("Server running on port 3000");
});

Running the index.js file should give you the below output.

Now let's add a route to handle our API requests. The endpoint will be /api/preview;

import express from "express";

//import cheerio and express
import { load } from "cheerio";
import axios from "axios";

//initialise express application
const app = express();

//api route to handle requests
app.get("/api/preview", async (req, res) => {
  try {
    //get url to generate preview, the url will be based as a query param.

    const { url } = req.query;
    /*request url html document*/
    const { data } = await axios.get(url);
    //load html document in cheerio
    const $ = load(data);

    /*function to get needed values from meta tags to generate preview*/
    const getMetaTag = (name) => {
      return (
        $(`meta[name=${name}]`).attr("content") ||
        $(`meta[propety="twitter${name}"]`).attr("content") ||
        $(`meta[property="og:${name}"]`).attr("content")
      );
    };

    /*Fetch values into an object */
    const preview = {
      url,
      title: $("title").first().text(),
      favicon:
        $('link[rel="shortcut icon"]').attr("href") ||
        $('link[rel="alternate icon"]').attr("href"),
      description: getMetaTag("description"),
      image: getMetaTag("image"),
      author: getMetaTag("author"),
    };

    //Send object as response
    res.status(200).json(preview);
  } catch (error) {
    res
      .status(500)
      .json(
        "Something went wrong, please check your internet connection and also the url you provided"
      );
  }
});

/* */

//tell express to expose server from port 4000
app.listen(4000, () => {
  console.log("Server running on port 4000");
});

Now we have everything ready for our backend, let's run and test it out.🥳🥳🥳

Press ctrl + ` on PCs and press cmd + ` on mac to open the VSCode terminal. Now run node index.js. You should get the output below.

Server running on port 4000.

Now you can open your browser or postman and make a request to localhost:3000/api/preview?url=<url of the website whose preview data you want>. You should receive a response like the one below.

Well done!!!. Thanks for joining me today, watch out for the next article in the series where we will integrate this api with a react frontend.

Kindly leave a comment if you need anything and please don't forget to share with your community.