Home > Software design >  fetch graphql data from nodejs to nextjs (SSR)
fetch graphql data from nodejs to nextjs (SSR)

Time:01-18

I have nextjs Project, where I use SSR for fetch data from nodejs(graphql) but it works only localhost(dev/production), When I upload the project on vercel I get "500: Internal Server Error", I will share my code and required details below:

I use "graphql-request" on Nextjs

import { gql, request } from "graphql-request";

export async function getServerSideProps(context) {

  const endPoint = "http://localhost:4000/";

  const query = gql`
    query {
      exactlyUser(id: "63c3cf0aea56b467893c92d3") {
        username
      }
    }
  `;

  const data = await request(endPoint, query);

  return {
    props: {
      data: data,
    },
  };
}

I also give you vercel Error:

[HEAD] /_next/data/U_aH1k5dl2EQA1IzXATL6/index.json
2023-01-17T16:52:11.277Z    ddd8e632-1ffa-4772-94c0-aa01e2348bb7    ERROR   FetchError: request to http://localhost:4000/ failed, reason: connect ECONNREFUSED 127.0.0.1:4000
    at ClientRequest.<anonymous> (/var/task/node_modules/node-fetch/lib/index.js:1491:11)
    at ClientRequest.emit (node:events:513:28)
    at Socket.socketErrorListener (node:_http_client:494:9)
    at Socket.emit (node:events:513:28)
    at emitErrorNT (node:internal/streams/destroy:151:8)
    at emitErrorCloseNT (node:internal/streams/destroy:116:3)
    at process.processTicksAndRejections (node:internal/process/task_queues:82:21) {
  type: 'system',
  errno: 'ECONNREFUSED',
  code: 'ECONNREFUSED',
  page: '/'
}
RequestId: ddd8e632-1ffa-4772-94c0-aa01e2348bb7 Error: Runtime exited with error: exit status 1
Runtime.ExitError

CodePudding user response:

Seems like when you deploy the Next.js app to Vercel, the API is not accessible. This is the cause of the "500: Internal Server Error" you're seeing.

Try to change the API endpoint URL to the publicly accessible URL of your GraphQL API, instead of using "http://localhost:4000/". This should allow the Next.js app to fetch data from the API when it's running on Vercel.

Avoid hardcoding the API endpoint.

  • Related