Hosna QasmeiH
Convex Community2y ago
2 replies
Hosna Qasmei

Is it possible to call a mutation in a Next.js API route?

I am trying to implement Stripe Oauth into my Next.js app. I get the users user id and access tokens from an api route, /api/stripe/verify.

When I get those values I wanted to create a row in my convex table, but the only way it work is with use client.
Wanted to know what the best approach for this is. Here is the code I'm referring too

import { NextResponse } from 'next/server';

import { stripe } from '@/lib/stripe';
import { useMutation, useQuery } from 'convex/react';

import { api } from '../../../../../convex/_generated/api';
import { Id } from '../../../../../convex/_generated/dataModel';

// Main POST handler
export async function POST(req: Request): Promise<NextResponse> {
  const addIntegration = useMutation(api.integrations.addIntegrationByUser);
  try {
    const body = await req.json();
    const code = body.codeId;

    const result = await stripe.oauth
      .token({
        grant_type: 'authorization_code',
        code: code,
      })
      .catch((err: unknown) => {
        console.log(err);
      });
    if (result) {
      await addIntegration({
        planId: '' as Id<'plans'>,
        userId: '',
        integration: '',
        value: [
          {
            stripeUserId: result.stripe_user_id,
            accessToken: result.access_token,
            refreshToken: result.refresh_token,
          },
        ],
      });
    }

    console.log(result);
    return NextResponse.json({ test: '' });
  } catch (error) {
    console.error('[PROJECT_POST]', error);
    return new NextResponse('Internal Server Error', { status: 500 });
  }
}
Was this page helpful?