Explain the Next.js Serverless Functions.

Explain the Next.js Serverless Functions.

Using serverless functions in Next.js lets you do different tasks without having to keep up a separate server. Here's how you can use serverless functions in Next.js to manage form submissions, process payments, and work with external APIs:

Handling Form Submissions:

Let's say you have a contact form in your Next.js application. You can use a serverless function to handle the form submission and send an email using a service like SendGrid. First, create a file in your Next.js project directory under /pages/api/contact.js:

// /pages/api/contact.js

import sgMail from '@sendgrid/mail';

export default async function handler(req, res) {
  if (req.method === 'POST') {
    const { name, email, message } = req.body;

    sgMail.setApiKey(process.env.SENDGRID_API_KEY);

    const msg = {
      to: 'your@email.com',
      from: email,
      subject: 'New Contact Form Submission',
      text: `Name: ${name}\nEmail: ${email}\nMessage: ${message}`,
    };

    try {
      await sgMail.send(msg);
      res.status(200).json({ success: true });
    } catch (error) {
      res.status(500).json({ error: 'Something went wrong.' });
    }
  } else {
    res.setHeader('Allow', ['POST']);
    res.status(405).end(`Method ${req.method} Not Allowed`);
  }
}

Processing Payments:

For processing payments, you might integrate with a service like Stripe. Here's how you can create a serverless function to handle payments:

// /pages/api/checkout.js

import stripe from 'stripe';

const stripe = new stripe(process.env.STRIPE_SECRET_KEY);

export default async function handler(req, res) {
  if (req.method === 'POST') {
    const { amount, token } = req.body;

    try {
      const paymentIntent = await stripe.paymentIntents.create({
        amount: amount,
        currency: 'usd',
        payment_method_types: ['card'],
        payment_method: token.id,
        confirm: true,
      });

      res.status(200).json({ success: true });
    } catch (error) {
      res.status(500).json({ error: 'Payment failed.' });
    }
  } else {
    res.setHeader('Allow', ['POST']);
    res.status(405).end(`Method ${req.method} Not Allowed`);
  }
}

Interacting with External APIs:

You can use serverless functions to interact with any external API. Here's a simple example of fetching data from a fictional API:

// /pages/api/external-data.js

export default async function handler(req, res) {
  try {
    const response = await fetch('https://api.example.com/data');
    const data = await response.json();
    res.status(200).json(data);
  } catch (error) {
    res.status(500).json({ error: 'Failed to fetch data.' });
  }
}

In these examples, serverless functions turn into API endpoints under /api in your Next.js app. You can use these endpoints in your frontend components with HTTP requests like fetch or axios. Remember to manage any needed authentication and check for errors in your frontend code.

Did you find this article valuable?

Support LingarajTechhub All About Programming by becoming a sponsor. Any amount is appreciated!