read ECONNRESET error occurs in nextjs geinitialProps when sending get request to api

Viewed 2378

This error occured in next.js app when i send a get request using axios in getInitialPros of _app.js file.

 if (typeof window === "undefined") {
    // user = await checkAuth(ctx);

    // const token = ctx.req.headers.cookie;

    console.log("TOKEN", ctx.req.headers);

    if (ctx.req && ctx.req.headers.cookie) {
      try {
        res = await axiosClient("get", { cookie: ctx.req.headers.cookie }).get(
          "/auth/currentuser"
        );

        user = res.data;
        console.log("USER IN SERVER SIDE", user);
        ctx.store.dispatch(setAuthenticatedUser(res.data));
      } catch (err) {
        console.log("ERROR in APP", err);
        // console.log("USER FOUND IN APP.JS", res.data);
        ctx.store.dispatch(removeAuthenticatedUser());
      }
    }
  } else {
    try {
      res = await axiosClient("get").get("/auth/currentuser");

      user = res.data;
      // await checkAuth(ctx);

      // await checkAuth(ctx,)
      console.log("IN CLIENT", res.data);
    } catch (err) {}
  }

this error occurred when the page is refreshed but it only occurs on server side, not in client side.

ERROR in APP Error: read ECONNRESET
        at TLSWrap.onStreamRead (internal/stream_base_commons.js:205:27) {
      errno: 'ECONNRESET',
      code: 'ECONNRESET',
      syscall: 'read',
      config: {
        url: '/auth/currentuser',
        method: 'get',
        headers: {
          Accept: 'application/json, text/plain, */*',
          cookie: 'token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOiI1ZjNhYTJlMmQxN2YxMzAxYTA0NGUxYTIiLCJpYXQiOjE1OTgyODUyMDMsImV4cCI6MTU5ODI4ODgwM30.qtaW-D9P6tJHzL1uHZs3wlzF39UPVkPTLEieuqaVEJY',
          'User-Agent': 'axios/0.19.2'
        },
        baseURL: 'https://tatkaladda.com/api/',
        transformRequest: [ [Function: transformRequest] ],
        transformResponse: [ [Function: transformResponse] ],
        timeout: 0,
        adapter: [Function: httpAdapter],
        xsrfCookieName: 'XSRF-TOKEN',
        xsrfHeaderName: 'X-XSRF-TOKEN',
        maxContentLength: -1,
        validateStatus: [Function: validateStatus],
        data: undefined
      },

this error only occurred in production app not in development mode.

1 Answers

Node.js is not aware of any baseURL. Your browser is. So on the server side you have to provide the full path, on the client side when using relative links they're relative to the base url, eg https://example.com By: Tim Neutkens - Co-author of Next.js and MDX

One of the suggested workaround is to use full path in the getInitialProps when using axios. In your case change this:

res = await axiosClient("get").get("/auth/currentuser");

to

res = await axiosClient("get").get("http://localhost:3000/auth/currentuser"); 
//or use external domian if you not on localhost i.e. https:api.example.com/auth/currentuser

If still this does not work, use axios API and set full path on baseUrl as follow:

// axios call
await axios({
    method: 'GET',
    url: 'http://abc.herokuapp.com/api/' //or baseURL: 'http://abc.herokuapp.com/api/'
)}

Have time! kindly read this, it might help: https://github.com/vercel/next.js/issues/5009

UPDATE

Also you can try to construct your baseURL from getInitialProps context

async getInitialProps({ req }) {
    const protocol = req.headers['x-forwarded-proto'] || 'http'
    const baseUrl = req ? `${protocol}://${req.headers.host}` : ''

    const res = await fetch(baseUrl + '/api/recent/1')
    ...
}
Related