#NextAuth Making Authorized Request

1 messages · Page 1 of 1 (latest)

surreal fossil
#

I'm using NextAuth, and in my page im making a request to create a new post, how can i make this api route handler protected using a middleware and the request to be secured (authenticated)

forest fossilBOT
#

Hi @surreal fossil. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

To secure your API route in Next.js using NextAuth, you can use the getSession function from NextAuth.js to check if the user is authenticated. Here's an example of how you can do this:

import { getSession } from 'next-auth/react';
import prisma from '../../../lib/prisma';

// POST /api/post
// Required fields in body: title
// Optional fields in body: content
export default async function handle(req, res) {
  const { title, content } = req.body;

  const session = await getSession({ req });

  // Check if the user is authenticated
  if (!session) {
    res.status(401).json({
      error: 'User is not authenticated',
    })
    return
  }

  const result = await prisma.post.create({
    data: {
      title: title,
      content: content,
      author: {
        connect: {
          email: session?.user?.email
        },
      },
    },
  });

  res.json(result);
}

In this example, the getSession function is used to get the current user session. If no session exists (meaning the user is not authenticated), the function returns a 401 status with an error message. If a session does exist, the function proceeds to create a new post using the Prisma Client^1^.

Please note that this is a basic example and you might need to adjust it according to your needs. For example, you might want to add more checks or handle errors differently.


Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: