Add Comments Support

Use Session Info

Now we are going to use session information inside our comments API. With that:

  • We allow only authenticated users to add comments
  • We can use currently logged in user's information for the comment

First, import following inside the pages/api/comments.js:

import { getSession } from 'next-auth/client'

Then replace the code inside if (req.method === 'POST') block with the following:

const session = await getSession({ req })

if (!session) {

const comment = {
    avatar: session.user.profile.avatar,
    content: req.body.content,

// Slow the API to demonstrate real life behavior
await new Promise((r) => setTimeout(r, 600))

await addComment(slug, comment)
return res.send(comment)

(Here's the final version of the file after all these changes.)

As you can see, only logged in users can add a comment.

Q: How can we add a comment with these changes?

šŸ™ We need your help

We need your help to keep maintain & add new content to this course. Here's how you can support us: