#Server actions

1 messages · Page 1 of 1 (latest)

unkempt prismBOT
#

Hi @primal finch. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

Yes, you can turn your API file that sends emails into a Server Action function in Next.js. To do this, you need to use the "use server" directive to mark the function as a Server Action. Below is an example of how you can modify your existing code to achieve this:

'use server';

import { NextResponse } from 'next/server';
import sgMail from '@sendgrid/mail';

const SENDGRID_API_KEY = process.env.SENDGRID_API_KEY;
const MY_EMAIL = process.env.MY_EMAIL;

if (!SENDGRID_API_KEY || !MY_EMAIL) {
  throw new Error(
    'Environment variables SENDGRID_API_KEY or MY_EMAIL are not set',
  );
}

sgMail.setApiKey(SENDGRID_API_KEY);

export async function sendEmail(request: Request) {
  if (request.method !== 'POST') {
    return new NextResponse('Method Not Allowed', { status: 405 });
  }
  try {
    const { name, email, message } = await request.json();

    const msg = {
      to: MY_EMAIL,
      from: 'no-reply@test.com',
      subject: 'New Contact Form Inquiry',
      html: `<strong>Name:</strong> ${name}<br><strong>Email:</strong> ${email}<br><strong>Message:</strong> ${message}`,
    };

    await sgMail.send(msg);

    return new NextResponse('Email sent successfully', { status: 200 });
  } catch (error) {
    console.error('Error sending email', error);
    return new NextResponse('Error sending email', { status: 500 });
  }
}

In this example, the sendEmail function is marked as a Server Action by placing the 'use server' directive at the top of the file. This allows the function to be executed on the server, handling the email sending process.

For more information on Server Actions and how to configure them, you can refer to the Next.js documentation on Server Actions and Mutations (https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions-and-mutations).

#

@primal finch kapa.ai is still learning and improving, please let us know how it did by reacting below

primal finch
#

@unkempt prism Awesome! Can you also turn this one to server actions as well?: import { NextResponse } from 'next/server';

import prisma from '@/app/libs/prismadb';
import getCurrentUser from '@/app/actions/getCurrentUser';

export async function POST(request: Request) {
const currentUser = await getCurrentUser();

if (!currentUser) {
return NextResponse.error();
}

const body = await request.json();
const {
title,
description,
imageSrc,
categories,
startDate,
endDate,
location,
locationLat,
locationLng,
country,
region,
ticketTypes,
imageSrcKey,
slug,
} = body;

const event = await prisma.event.create({
data: {
title,
description,
imageSrc,
categories,
startDate,
endDate,
location,
locationLat,
locationLng,
country,
region,
userId: currentUser.id,
ticketTypes: {
create: ticketTypes,
},
imageSrcKey,
slug,
},
});
return NextResponse.json({ event });
}

unkempt prismBOT
#

Let me check the knowledge base for you. One moment! :books:

#

Sure! You can turn your existing API function into a Server Action by using the "use server" directive. Here is how you can modify your code:

'use server';

import { NextResponse } from 'next/server';
import prisma from '@/app/libs/prismadb';
import getCurrentUser from '@/app/actions/getCurrentUser';

export async function createEvent(request: Request) {
  const currentUser = await getCurrentUser();

  if (!currentUser) {
    return NextResponse.error();
  }

  const body = await request.json();
  const {
    title,
    description,
    imageSrc,
    categories,
    startDate,
    endDate,
    location,
    locationLat,
    locationLng,
    country,
    region,
    ticketTypes,
    imageSrcKey,
    slug,
  } = body;

  const event = await prisma.event.create({
    data: {
      title,
      description,
      imageSrc,
      categories,
      startDate,
      endDate,
      location,
      locationLat,
      locationLng,
      country,
      region,
      userId: currentUser.id,
      ticketTypes: {
        create: ticketTypes,
      },
      imageSrcKey,
      slug,
    },
  });
  return NextResponse.json({ event });
}

In this example, the createEvent function is marked as a Server Action by placing the 'use server' directive at the top of the file. This allows the function to be executed on the server, handling the event creation process.

For more information on Server Actions and how to configure them, you can refer to the Next.js documentation on Server Actions and Mutations (https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions-and-mutations).

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:

#

@primal finch kapa.ai is still learning and improving, please let us know how it did by reacting below

#

Let me check the knowledge base for you. One moment! :books:

#

Yes, you can turn your GET API request into a Server Action. Below is an example of how you can modify your existing code to achieve this:

First, ensure your revalidation action is correctly set up. Here is your revalidateEvents action:

'use server';

import { revalidatePath } from 'next/cache';

interface Path {
  path: string;
  type: 'page';
}

export default async function revalidateEvents() {
  const paths: Path[] = [
    { path: '/events/[eventSlug]/[eventId]', type: 'page' },
    { path: '/events/category/[category]/[region]', type: 'page' },
    { path: '/events/category/[category]', type: 'page' },
    { path: '/events/region/[region]', type: 'page' },
  ];

  paths.forEach(({ path, type }) => {
    revalidatePath(path, type);
  });
}

Next, you can create a Server Action for your GET request. Here is how you can modify your existing GET API request to use the revalidateEvents action:

'use server';

import { NextRequest, NextResponse } from 'next/server';
import revalidateEvents from '@/app/actions/revalidateEvents';

export async function revalidate(request: NextRequest) {
  const secret = request.nextUrl.searchParams.get('secret');

  if (secret !== process.env.NEXT_PUBLIC_REVALIDATION_SECRET) {
    return NextResponse.json({ message: 'Invalid secret' }, { status: 401 });
  }

  await revalidateEvents();

  return NextResponse.json({ message: 'Revalidation triggered' });
}

In this example, the revalidate function is marked as a Server Action by placing the 'use server' directive at the top of the file. This allows the function to be executed on the server, handling the revalidation process.

#

For more information on Server Actions and how to configure them, you can refer to the Next.js documentation on Server Actions and Mutations (https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions-and-mutations).

If you need to call this Server Action from a Client Component, you can import it and use it as shown in the convention section (https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions-and-mutations#convention) of the documentation.

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: