Search code examples
apinext.jsnetlify

Call Nextjs API from within Netlify function


I got a serverless Netlify function like this:

exports.handler = async function(event, context) {
    return {
        statusCode: 200,
        body: JSON.stringify({message: "Hello World"})
    };
}

When called by this url <site-name>/.netlify/functions/helloworld I do get the message {"message":"Hello World"}

I also got a pages/api/mailingList.js Nextjs API endpoint:

const axios = require('axios');
 
export default async function handler(req, res) {

 //console.log(req.query.mail);

 if (req.method === "PUT") {
   axios
     .put(
       "https://api.sendgrid.com/v3/marketing/contacts",
       {
         contacts: [{ email: `${req.query.mail}` }],
         list_ids: [process.env.SENDGRID_MAILING_LIST_ID],
       },
       {
         headers: {
           "content-type": "application/json",
           Authorization: `Bearer ${process.env.SENDGRID_API_KEY}`,
         },
       }
     )
     .then((result) => {
       res.status(200).send({
         message:
           "Your email has been successfully added to the mailing list. Welcome 👋",
       });
     })
     .catch((err) => {
       res.status(500).send({
         message:
           "Oups, there was a problem with your subscription, please try again or contact us",
       });
       console.error(err);
     });
  }
}

This mailing list API endpoint, do work when using curl from the terminal with PUT as the method:

curl -X PUT -d [email protected]  https://netlify.app/api/mailingList

The API endpoint also work from the URL (/api/[email protected]) when removing the if (req.method === "PUT") { part from the mailingList.js

However, I am NOT able to get the API endpoint to be called from within the Netlify function.

(Preferably the mailingList API should be possible to call multiple times with different mailing list IDs from the Netlify function helloworld.js based on different logic /api/[email protected]&listid=xxx)

To get the API endpoint to be called at all, from the function, I have tried adding a axios call from the helloworld.js to mailingList.js like this

const axios = require('axios');

exports.handler = async function(event, context) {


    const mail = "[email protected]";
    // add to mailinglist
    axios
    .put("/api/mailingList?mail="+mail)
    .then((result) => {
      if (result.status === 200) {
        toast.success(result.data.message);
      }
    })
    .catch((err) => {
      console.log(err);
    });

}

This result in the following error from the browser: error decoding lambda response: invalid status code returned from lambda: 0 (I do not get any error msg from the Netlify log, either helloworld.js or mailingList.js)

Clearly, there is something wrong with how I call the mailigList.js from helloworld.js. Would greatly appreciate if some one could give me some advice and show me what I am doing wrong.

How can I call the API endpoint (mailigList.js) from within the Netlify function helloworld.js? (Preferably multiple times with different mailing list IDs: /api/[email protected]&listid=xxx)


Solution

  • Found the solution in this article: https://travishorn.com/netlify-lambda-functions-from-scratch-1186f61c659e

    const axios = require('axios');
    
    const mail = "[email protected]";
    
    
    exports.handler = (event, context, callback) => {
        axios.put("https://<domain>.netlify.app/api/mailingList?mail="+mail)
          .then((res) => {
            callback(null, {
              statusCode: 200,
              body: res.data.title,
            });
          })
          .catch((err) => {
            callback(err);
          });
      };