Using now serveless functions with frontity

Hi!! :wink:

How can I use Now serveless functions with frontity? Some example?

I’ve created a root directory called api and inside I put a file just to test the request like in: https://zeit.co/docs/v2/serverless-functions/introduction

Or I need move the folder to src theme directory?

Best regards

Hi @christian.nascimento :wave:

Thanks for your patience. In order to be able to use the NOW serverless functions you’d need to modify your now.json file to:

  1. Use the default @now/node builder for the /api files
  2. Remap the routes so that your frontity site can run under the / and but the requests to /api are routed by NOW to your serverless functions.

You can keep your functions in the /api folder as you have done so far.

// now.json

{
  "version": 2,
  "builds": [
    {
      "src": "api/*.js",
      "use": "@now/node"
    },
    {
      "src": "package.json",
      "use": "@frontity/now"
    }
  ],
  "routes": [
    {
      "src": "/api/(.*)",
      "headers": { "cache-control": "no-cache" },
      "dest": "/api/$1.js"
    },
    {
      "src": "/static/(.*)",
      "headers": { "cache-control": "public,max-age=31536000,immutable" },
      "dest": "/static/$1"
    },
    { "src": "/favicon.ico", "dest": "favicon.ico" },
    {
      "src": "($|/.*)",
      "headers": { "cache-control": "s-maxage=1,stale-while-revalidate" },
      "dest": "/server.js"
    }
  ]
}

Let me know if that helps!

2 Likes

OMG! This is awesome! :smiley: Nice to see stale-while-revalidade in configuration. Thanks! :wink:

4 Likes

Hi, @mmczaplinski!

I created my serveless function but I dont know whats is wrong in my code.

const axios = require("axios");

module.exports = async function(req, res) {
  // Set CORS headers
  res.setHeader("Content-Type", "application/json");
  res.setHeader("Access-Control-Allow-Origin", "*");
  res.setHeader("Access-Control-Request-Method", "*");
  res.setHeader("Access-Control-Allow-Methods", "POST");
  res.setHeader("Access-Control-Allow-Headers", "*");

  if (req.method === "POST") {
    const { body } = req;

    const url =
      "https://cloud.example.com.br/cadastrar";

    try {
      const resp = await axios.post(url, body, {
        headers: {
          t: "token"
        }
      });
      // console.log(body);
      res.status(200).json(resp.data);
    } catch (error) {
      console.log("ERROR", error);
      res.status(400).json(error.response.data);
    }
  }
};

I’m getting a error code: NO_STATUS_CODE_FROM_FUNCTION

If I remember right you need to return either the response or the JSON data. It’s been a while since I worked with now functions :confused:

3 Likes

Thanks @orballo! Everything works fine! :smiley:

1 Like