0

I'm developing a integration with stripe in my nextjs aplication. Currently I'm trying to redirect the user to the checkout process, however, for that I need to get the session information in my 'subscribe.ts' file inside /pages/api.

I'm using getSession for that, here's my subscribe.ts file:

import { NextApiRequest, NextApiResponse } from "next";
// import { unstable_getServerSession } from "next-auth/next";
import { getSession } from "next-auth/react";
import { stripe } from "services/stripe";
// import { authOptions } from "./auth/[...nextauth]";

export default async (req: NextApiRequest, res: NextApiResponse) => {
    if(req.method == 'POST') {
        console.log(req, res);
        const session = await getSession({ req });
        console.log(req.cookies, session);
        // console.log(session);

        if(!session) return;

        const stripeCustomer = await stripe.customers.create({
            email: session.user.email,
        })

        const stripeCheckoutSession = await stripe.checkout.sessions.create({
            customer: stripeCustomer.id,
            payment_method_types: ['card'],
            billing_address_collection: 'required',
            line_items: [
                { price: 'price_1Kn2z8HXoO2e9eo5NaPFzRV1', quantity: 1 }
            ],
            mode: 'subscription',
            allow_promotion_codes: true,
            success_url: process.env.STRIPE_SUCCESS_URL,
            cancel_url: process.env.STRIPE_CANCEL_URL
        });

        return res.status(200).json({ sessionId: stripeCheckoutSession.id });
    } else {
        res.setHeader('Allow', 'POST');
        res.status(405).end('Method not allowed');
    }
}

The user makes login using the github integration from nextauth.

I've tried using the 'unstable_getServerSession' function but it returned null as well. After searching for a while I found that maybe there was some issue with the cookies from the request, but on the console.log the cookies are correctly tracked by the variable.

What am I doing wrong here?

// Edit: my [...nextauth].js

import { query as q } from 'faunadb';

import NextAuth from "next-auth";
import GithubProvider from "next-auth/providers/github";

import { Fauna } from "services/fauna";

export const authOptions = {
    providers: [
        GithubProvider({
            clientId: process.env.GITHUB_ID,
            clientSecret: process.env.GITHUB_SECRET,
            authorization: { params: { scope: 'read:user' } }
        }),
    ],
    callbacks: {
        async signIn({ user, account, profile }) {
            const { email } = user;

            try {
                await Fauna.query(
                    q.If(
                        q.Not(
                            q.Exists(
                                q.Match(
                                    q.Index('user_by_email'), 
                                    q.Casefold(user.email)
                                )
                            )
                        ),
                        q.Create(
                            q.Collection('users'),
                            { data: { email } }
                        ),
                        q.Get(
                            q.Match(
                                q.Index('user_by_email'), 
                                q.Casefold(user.email)
                            )
                        )
                    )
                );

                return true;

            } catch (error) {
                console.log(error);
                return false;
            }
        }
    }
};
export default NextAuth(authOptions);
  • Can you share `[...nextauth].ts` code? – ivanatias Oct 14 '22 at 05:25
  • Hi @ivanatias thanks for replying. I've edited the description with the [...nextauth].js code. – Lucas Marthins Oct 14 '22 at 23:42
  • 1
    I think the issue is that you are not specifying a `session` callback in `[...nextauth].ts`, so the session data is never returned when you use `getSession`. Also, `getSession` is mostly for client-side use, so `unstable_getServerSession` should be used instead on your API endpoint. Regarding the session issue, see [docs](https://next-auth.js.org/configuration/callbacks#session-callback) for reference. – ivanatias Oct 15 '22 at 00:19
  • I updated my callbacks and also changed getSession for unstable_getServerSession but no success. I also deleted .next folder to make sure there was no cache being applied. – Lucas Marthins Oct 15 '22 at 15:21

0 Answers0