Hosna Qasmei
Hosna Qasmei10mo ago

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 });
}
}

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 });
}
}
2 Replies
Rayy
Rayy10mo ago
Have you tried fetchMutation? You can check the docs in here, https://docs.convex.dev/client/react/nextjs/server-rendering
Next.js Server Rendering | Convex Developer Hub
Next.js automatically renders both Client and Server Components on the server
Hosna Qasmei
Hosna QasmeiOP10mo ago
Yup that's what I was looking for, perfect! Convex is the GOAT , thanks @Rayy !

Did you find this page helpful?