Atharva Deosthale Web Developer and Designer | JavaScript = ❤ | MERN Stack Developer

Build a privacy-focused comments section on your Next.js blog

5 min read 1627

When you are creating a blog website, one of the things that should always concern you is the comments section. You can try to use your own implementation, but it may not be the best option if you don’t have much time and want to keep things simple. A great solution is Remark42, a commenting engine that gives you the control so you can host the comments section on your own server.

You can also implement Google login in Remark42 so that your readers don’t have to go through the tedious process of entering their email and password. Comments on each page are tracked separately, so you don’t need to keep track of blog posts for comments.

Today, we are going to implement Remark42 in a simple blog application made using Next.js and Tailwind CSS. We will only be focusing on the comments section part of the blog. Remark42 doesn’t have native implementation for Next.js, but I have built a workaround that shouldn’t cause any problems.

Requirements

  • Working knowledge of React
  • Working knowledge of Next.js
  • NodeJS installed on your machine
  • Code editor – I prefer Visual Studio Code
  • A Google account – we will be using this for dealing with Google Authenticator
  • A MacOS, Windows, or Linux system. I am using MacOS, so the instructions of setting up the server should work for MacOS and Linux users. Windows users can use WSL to use a Linux terminal and follow the exact same steps

If you get stuck in the tutorial, or need reference to the code, feel free to refer to the GitHub repository.

Setting up a Remark42 server

Let’s set up the Remark42 server. This server will be the home for all of our comments, and also deal with authentication. Head to this link and download the binary relevant to your operating system. For MacOS users, the binary should look similar to this: remark42.darwin-amd64.tar.gz.

Extract the tar.gz archive you just downloaded using a suitable extractor program and launch a terminal inside the extracted folder. Write the following command to convert the binary to an executable so that it can be run by the system:

chmod +x remark42.darwin-amd64

Make sure you replace the name of the file according to the operating system you’re running. Now that you have converted the binary into an executable, you are able to run the server using the following command:

./remark42.darwin-amd64 server --site=remark123 --secret=12345 --url=http://localhost:8080

Make sure you use a unique secret here because it will be used in signing your JSON web tokens for authentication. Provide a site ID too; I’m providing remark123. Once you run the command, the server will start running, and if you visit http://localhost:8080/web, you should see a demo like this:

remark42 demo page

However, you cannot make any comments for now, because we need a proper way to authenticate users in our blog, which is required before they can comment. In this case we will be using Google authentication, however, there are a many ways of authentication supported by Remark42, which you can see here.



Creating a Google OAuth2 client

First, go to Google Cloud Console. Create a new project if you don’t have one, then click on Credentials on the sidebar. Now you should be presented with the following screen:

Google cloud console credentials page

Click on Create Credentials on the top. You should be presented with a list of options:

credentials options

Click on OAuth client ID, because that is what is used for authentication with Google. If you do not have an OAuth consent screen, you will be asked to create one:

oauth consent screen

Click on External and then Create. Now you will be asked for some details about your project:

oauth app information

Fill in the relevant details and submit the form. Now, go back to Credentials, create a new OAuth Client ID, and now you shouldn’t be asked to create a consent screen. Add the following details when prompted (these details are according to Remark42’s documentation):

authorized javascript origins

Now you should get your Client ID and Client Secret. Take note of them, but do not share these details with anyone.

Now kill the running Remark42 server and let’s start it again, but adding the Google credentials this time:

./remark42.darwin-amd64 server --secret=12345 --url=http://localhost:8080 --auth.google.cid=392614297779-s9sn37kc587341uk8b2olhpiigg6v9kh.apps.googleusercontent.com --auth.google.csec=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 --site=remark123

Make sure you replace my credentials with your own. Now hit Enter and the server will start running.

Creating a Next.js app and integrating Remark42

Navigate to a safe directory and run the following command to create a new Next.js app:


More great articles from LogRocket:


npx create-next-app remark42-app --example with-tailwindcss

You can replace remark42-app with any suitable name, as it’s a project name. We are using with-tailwindcss example so that we can get Tailwind CSS pre-installed and we don’t need to worry much about styling.

Go into the pages directory and open index.tsx file, then update the layout as follows:

import Head from 'next/head'
export default function Home() {
  return (
    <div className="flex min-h-screen flex-col items-center justify-center py-2">
      <Head>
        <title>Create Next App</title>
        <link rel="icon" href="/favicon.ico" />
      </Head>
      <div className="text-3xl font-bold">First article</div>
      <div className="text-lg">First article content</div>
      <div id="remark42">{''}</div>
    </div>
  )
}

This will be the basic layout of our dummy blog post on the homepage. We have used {''} under a div because Remark42 causes issues with Next.js and this is a quick fix to one of those issues.

Now let’s add the script near the end of the layout:

<script
  dangerouslySetInnerHTML={{
    __html: `
    const remark_config = {
      host: 'http://localhost:8080',
      site_id: 'remark123',
    };
    window.remark_config = remark_config;
          !function(e,n){for(var o=0;o<e.length;o++){var r=n.createElement("script"),c=".js",d=n.head||n.body;"noModule"in r?(r.type="module",c=".mjs"):r.async=!0,r.defer=!0,r.src=remark_config.host+"/web/"+e[o]+c,d.appendChild(r)}}(remark_config.components||["embed"],document);`,
  }}
></script>

Remember to change the host and site_id when you shift to production. Also, it is necessary for the object to be named remark_config because Remark42 looks for this object when initializing.

Because we are running this code in Next.js, we do a quick fix by attaching remark_config to the window object so that the code works properly. And the rest of the code that doesn’t look so pleasant is a script from Remark42 to do everything else. If, for some reason, this code does not work, it might’ve changed and you might need to find the new script from Remark42’s documentation.

Now, run the Next.js development server by running the following command in the terminal:

npm run dev

Now the server should be started. Visit http://localhost:8000 to view the page:

Example article that reads "first article" and a comment box

Now you can authenticate and add comments to the page:

Sample "first article" with comment from authorized user

Now, let’s create a new file called second.js in the pages directory to simulate another post in the blog:

import React from 'react'
function Second() {
  return (
    <div className="flex min-h-screen flex-col items-center justify-center py-2">
      <div className="text-3xl font-bold">Second article</div>
      <div className="text-lg">Second article content</div>
      <div id="remark42">{''}</div>
      <script
        dangerouslySetInnerHTML={{
          __html: `
          const remark_config = {
            host: 'http://localhost:8080',
            site_id: 'remark123',
          };
          window.remark_config = remark_config;
          !function(e,n){for(var o=0;o<e.length;o++){var r=n.createElement("script"),c=".js",d=n.head||n.body;"noModule"in r?(r.type="module",c=".mjs"):r.async=!0,r.defer=!0,r.src=remark_config.host+"/web/"+e[o]+c,d.appendChild(r)}}(remark_config.components||["embed"],document);`,
        }}
      ></script>
    </div>
  )
}
export default Second

It’s similar to the code for the first post. Ideally, you would fetch the post from the database and the URL would be dynamic so you won’t have to deal with repetitiveness. We are doing this approach just to make things simpler.

Now if you visit http://localhost:3000/second, you should see that the original comment we made isn’t there anymore, because it’s a completely different page. This is because Remark42 handles comments for different pages for us.

Some additional configurations

You can modify the looks and behavior of Remark42 with the various configurations it provides us. For example, if you want to implement dark mode, you simply have to update remark_config as follows:

const remark_config = {
  host: 'http://localhost:8080',
  site_id: 'remark123',
  theme: 'dark',
};

This will enable dark mode, and your comments section should look like this:

Comment box in dark mode

You can also enable simple view, which helps keep things simple in the comments section. In simple view, not a lot of JavaScript is used, and only necessary components are loaded:

const remark_config = {
  host: 'http://localhost:8080',
  site_id: 'remark123',
  simple_view: true,
};

This should look like following:

comment box in simple view

Notice here there’s no support for formatting text. You can find the rest of the configurations here.

Conclusion

Remark42 is a wonderful tool if you are creating a blog but don’t want to make things too complex. You can also try to play with the configurations to modify how it functions overall, and fit it in your blog website accordingly.

Again, if you get stuck in the tutorial or need reference to the code, here’s the GitHub repository.

LogRocket: Full visibility into production Next.js apps

Debugging Next applications can be difficult, especially when users experience issues that are difficult to reproduce. If you’re interested in monitoring and tracking state, automatically surfacing JavaScript errors, and tracking slow network requests and component load time, try LogRocket.

LogRocket is like a DVR for web and mobile apps, recording literally everything that happens on your Next app. Instead of guessing why problems happen, you can aggregate and report on what state your application was in when an issue occurred. LogRocket also monitors your app's performance, reporting with metrics like client CPU load, client memory usage, and more.

The LogRocket Redux middleware package adds an extra layer of visibility into your user sessions. LogRocket logs all actions and state from your Redux stores.

Modernize how you debug your Next.js apps — .

Atharva Deosthale Web Developer and Designer | JavaScript = ❤ | MERN Stack Developer

Leave a Reply