API resolved without sending a response in Nextjs

Viewed 55713

I have to make same changes in my nextjs project because my enpoint API doesn't support many calls and I would like to make a refresh from the original data every 3 min.

I implemented API from nextjs: I create a pages/api/data and inside I make the call to my endpoint, and in my getInitialProps inside index call to data file.

The get works okey, but I have 2 problems:

1: I have and alert message that says:

API resolved without sending a response for /api/data, this may result in stalled requests.

2: It dosen 't reload data after 3 min..I supouse it is beacuse Cache-Control value...

This is my code:

pages/api/data

import { getData } from "../../helper";

export default async function(req, res) {
  getData()
    .then(response => {
      res.statusCode = 200
      res.setHeader('Content-Type', 'application/json');
      res.setHeader('Cache-Control', 'max-age=180000');
      res.end(JSON.stringify(response))
    })
    .catch(error => {
      res.json(error);
      next();
    });
};

pages/index

import React, { useState, useEffect } from "react";
import fetch from 'isomorphic-unfetch'

const Index = props => {

  return (
    <>Hello World</>
  );
};

 Index.getInitialProps = async ({ res }) => {
  const response = await fetch('http://localhost:3000/api/data')
  const users = await response.json()
  return { users }
};

export default Index;
5 Answers

You should return a Promise and resolve/reject it.

Example:

import { getData } from "../../helper";

export default async function(req, res) {
  return new Promise((resolve, reject) => {
    getData()
      .then(response => {
        res.statusCode = 200
        res.setHeader('Content-Type', 'application/json');
        res.setHeader('Cache-Control', 'max-age=180000');
        res.end(JSON.stringify(response));
        resolve();
      })
      .catch(error => {
        res.json(error);
        res.status(405).end();
        resolve(); // in case something goes wrong in the catch block (as vijay commented)
      });
  });
};
import { getData } from "../../helper";

export default async function (req, res) {
  try {
    const response = await getData();
    res.statusCode = 200;
    res.setHeader('Content-Type', 'application/json');
    res.setHeader('Cache-Control', 'max-age=180000');
    res.end(JSON.stringify(response));
  }

  catch (error) {
    res.json(error);
    res.status(405).end();
  }
}

For me it was necessary to return the result, even though the result was given to the client without return:

Before: res.status(405).json({ message: 'Method not allowed.' });

After, error resolved: return res.status(405).send('Method not allowed.');

[EDIT]: corrected to use send instead of json for error return value.

You can use 'next-connect' library which eliminates the necessity of returning a promise in this scenario. If you like express.js's route->middleware->endpoint pattern this library is what you are looking for. It also provides global error handling out of the box! [next-connect docs]

Example:

import nc from 'next-connect'

function onError(err, req, res, next) {
  logger.log(err);

  res.status(500).end(err.toString());
  // OR: you may want to continue
  next();
}

const handler = nc({ onError });

handler
  .use((req, res, next) => {
    if(!req.user){
      throw new Error("oh no!");
      // or use next
      next(Error("oh no"));
    }
  })
  .get((req, res) => {
    res.end("success")
  })
export default async function handler(req, res) {
  return new Promise(async (resolve) => {
    switch (req.method) {
      case "GET": {
        try {
          let response = await fetch(
            "https://jsonplaceholder.typicode.com/todos/1"
          );
          res.status(200).send(await response.json());
          return resolve();
        } catch (error) {
          res.status(500).end();
          return resolve();
        }
      }
    }
    res.status(405).end();
    return resolve();
  });
}
Related