Challenges

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) {
    res.status(401).send('Unauthorized')
    return;
}

const comment = {
    userId: session.user.id,
    name: session.user.profile.name,
    avatar: session.user.profile.avatar,
    content: req.body.content,
    createdAt: Date.now()
}

// 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?
authenticating...

šŸ™ We need your help

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