0

I'm learning to program. For practice, I'm creating a simple app where users can login and save their notes. It's a nextjs app with vercel postgres, and prisma. I'm using nextauth for authentication.

I think I managed to add prisma and also nextauth. Now I try to make a simple request to the database that adds a note that belongs to a user.

The problem is that I'm getting a typescript error that says: "Type 'string | null | undefined' is not assignable to type 'string'. Type 'undefined' is not assignable to type 'string'."

It comes from the email: session?.user?.email row in the code below.

Has anyone experienced this kind of issue and how have you solved it?

import { options } from "../../api/auth/[...nextauth]/options";
import { getServerSession } from "next-auth/next";
import db from "../../api/db";

export default async function Page() {
  const session = await getServerSession(options);
  if (!session) return;

  async function addNote() {
    "use server";
    const res = await db.notes.create({
      data: {
        content: "Apple",
        category: "Fruit",
        owner: {
          connect: {
            email: session?.user?.email,
          },
        },
      },
    });
    return res;
  }

  const result = await addNote();
  console.log(result);
  return <></>;
}

I think I could somehow check that it is a string beforehand. Or, I could use type assertion, because I don't know how could it not be a string.

But I think I'm doing something wrong if I do it that way.

2 Answers 2

1

Three possible solutions: 1- You could check for the user and the email like:

if (session.user && session.user.email){
....
}

2- Or if you are sure there will be a user (like the route is protected..etc), you can use assertion like:

 email: (session?.user?.email as strin),

3- or you can use a fixed string value in case email is undefined or null like:

 email: session?.user?.email || "",
Sign up to request clarification or add additional context in comments.

Comments

0

It seems your code requires email to be of type string. You can convert that and make the required type include null and undefined because email might not always be available.

For now, a quick fix would be to covert email: session?.user?.email into email: session?.user?.email as unknown as string. This will force the type of email to be string so it is compatible with what is required.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.