Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Unauthorized Error when Creating a New Post #5574

Open
Bakhtiar85 opened this issue Dec 8, 2023 · 1 comment
Open

Unauthorized Error when Creating a New Post #5574

Bakhtiar85 opened this issue Dec 8, 2023 · 1 comment

Comments

@Bakhtiar85
Copy link

Bakhtiar85 commented Dec 8, 2023

Description

I am encountering an unauthorized error when attempting to create a new post, even though I am logged in via GitHub. Upon modifying the code in pages/api/post/index.ts to log the session, I observed the following error:

{
    "message": "you are not authorized",
    "error": {
        "name": "PrismaClientValidationError",
        "clientVersion": "5.7.0"
    },
    "data": null
}

Modified code to observe the issue

// POST /api/post
// Required fields in body: title
// Optional fields in body: content
export default async function handle(req: NextApiRequest, res: NextApiResponse) {
  const { title, content } = req.body;
  const session = await getSession({ req });
  console.log('POST Session: ', session);

  try {
    const result = await prisma.post.create({
      data: {
        title: title,
        content: content,
        // author: { connect: { email: session?.user?.email } }, // to by pass the session auth
        author: { connect: { email: "mypersonal@email.com"} },
      },
    });
    res.status(201).send({ message: 'post created successfully', error: null, data: result});
  } catch (err) {
    res.status(401).send({ message: 'you are not authorized', error: err, data: null});
  }
}

on the other hand when I delete a post and log session then I get user information there.
whereas if I do console.log('POST Session: ', session); above I get null

Node version: v21.3.0
NPM version: 10.2.4
npm list next:
├─┬ next-auth@4.24.5
│ └── next@13.5.6 deduped
├─┬ next-superjson@0.0.4
│ ├─┬ babel-plugin-superjson-next@0.4.5
│ │ └── next@13.5.6 deduped
│ └── next@13.5.6 deduped
└── next@13.5.6

@ghost
Copy link

ghost commented Dec 8, 2023

I solved this issue by deleting the req.body.

  const { title, content } = req.body;
  delete req.body;
  const session = await getSession({ req });

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant