Search code examples
node.jsexpresshref

SEO friendly links with Express JS


I am trying to build a blog website using Node + Express JS. I would like to make it SEO friendly, because currently the links to the blogs are using Ids of the database. For example:

localhost:3000/posts/1

However, I want to have a link like this:

localhost:3000/posts/my-adventure/

I am following dev.to website and I see that they are using href not with ids, but with the article names. I am puzzled here because this doesn't seem to be efficient from performance perspective as the database would have to be searched by long strings?

<a href="/djangostars/choosing-python-for-web-development-top-16-pros-and-cons-4c4k" id="article-link-185734" class="index-article-link" aria-label="Main Story" data-featured-article="articles-185734">
</a>

I would like to ask your help on how I could implement this in my application. Currently I am using this type of route:

router.get("/:id", async (req, res, next) => {
  const post = await db.query(
    "SELECT * FROM posts WHERE id = $1",
    req.params.id
  );
  res.render("readPost", { title: post.title, post: post });
});

Solution

  • One way (I prefer this)

    append the 'id' to the URL to make it unique. (sth like localhost:3000/posts/my-adventure-1/)

    Your code snippet mayn't change, except the db column type (if you have used number)

    You can use slugify.

    Another way

    router.get("/:slug/:id", async (req, res, next) => {
      const post = await db.query(
        "SELECT * FROM posts WHERE id = $1",
        req.params.id
      );
      res.render("readPost", { title: post.title, post: post });
    });
    

    https://medium.com/@thiscodeworks.com/implementing-url-slugs-on-express-node-js-5f5890431dea