prisma / blogr-nextjs-prisma

111 stars 83 forks source link

Add new Post/Draft not allowed because authentication issues #35

Open prtpj1 opened 7 months ago

prtpj1 commented 7 months ago

Hi, I got help with this issue here: https://github.com/vercel/next.js/discussions/60536 I was getting this error everytime I tries to create a draft:

[next-auth][error][CLIENT_FETCH_ERROR] 
https://next-auth.js.org/errors#client_fetch_error undefined {
  error: {},
  url: 'http://localhost:3000/api/auth/session',
  message: undefined
}

And with 808vita helps I had to change this files to work: draft.tsx

export const getServerSideProps: GetServerSideProps = async ({ req, res }) => {
    const session = await **getServerSession(req, res, authHandler)**;

    if (!session) {
        res.statusCode = 403;
        return { props: { drafts: [] } };
    }

    const drafts = await prisma.post.findMany({
        where: {
            author: { email: session.user.email },
            published: false,
        },
        include: {
            author: {
                select: { name: true },
            },
        },
    });
    return {
        props: { drafts },
    };
};

index.ts

**interface Session {
    user?: {
        email?: string,
    }
}**

export default async function handle(req: any, res: any) {
    const { title, content } = req.body;

    const session: Session = await **getServerSession(req, res, authHandler);**
    if (!session || !session.user.email) {
        res.status(401).json({ error: 'You must be logged in to create a post.' });
        return;
    }

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

[...nextauth].ts

export const authHandler: NextAuthOptions = {
    providers: [
        GitHubProvider({
            clientId: process.env.GITHUB_ID,
            clientSecret: process.env.GITHUB_SECRET,
        }),
    ],
    adapter: PrismaAdapter(prisma),
    secret: process.env.SECRET,
}

export default NextAuth(authHandler);

Instead of:

const authHandler: NextApiHandler = (req, res) => NextAuth(req, res, options);
export default authHandler;

const options = {
    providers: [
        GitHubProvider({
            clientId: process.env.GITHUB_ID,
            clientSecret: process.env.GITHUB_SECRET,
        }),
    ],
    adapter: PrismaAdapter(prisma),
    secret: process.env.SECRET,
}

The issue was fixed with 808vita's help, but I would like to ask if there is a possibility to update the tutorial instructions, so new devs (as me) wont pass through all this troubles trying to learn more about NextJS