Add Comments Support

Add Comments API

First of all, we are going to create a Next.js API route to get and create comments.

For that, create a file called pages/api/comments.js and add the following content:

import { getComments, addComment } from '../../lib/data'

export default async function comments(req, res) {
    const {slug} = req.query

    if (req.method === 'GET') {
        const comments = await getComments(slug)
        return res.send(comments)
    if (req.method === 'POST') {
        const comment = {
            userId: 'user-id',
            name: 'The User',
            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)

    res.status(404).send('Unsupported Method')

Let's try this out:

Run your app and invoke this curl command inside a terminal: (It will fetch comments related to a slug called hello-world.)

curl  http://localhost:3009/api/comments?slug=hello-world

Now create a comment by invoking the following command: (Here we make a POST request with a JSON payload)

curl \
    -X POST \
    -H "Content-Type: application/json" \
    -d '{"content": "This is it"}'  \

Now try to get comments again with:

curl  http://localhost:3009/api/comments?slug=hello-world

Try to create two more comments and view those.

Q: Which is the false statement based on your results?

Let's have one more question:

Q: This API has a major issue, what's that?

šŸ™ We need your help

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