2

My application is working on localhost without problem. When I deploy it tho vercel through github it throws error. My building logs are like that


Cloning github.com/sayinmehmet47/electronic-products47 (Branch: main, Commit: 2ae970b)
Cloning completed: 738.588ms
Analyzing source code...
Installing build runtime...
Build runtime installed: 2.071s
Looking up build cache...
Build Cache not found
Installing dependencies...
yarn install v1.22.17
[1/4] Resolving packages...
[2/4] Fetching packages...
[3/4] Linking dependencies...
warning "next > styled-jsx > @babel/plugin-syntax-jsx@7.14.5" has unmet peer dependency "@babel/core@^7.0.0-0".
warning "react-chrono > @emotion/styled > @emotion/babel-plugin@11.7.2" has unmet peer dependency "@babel/core@^7.0.0".
warning "react-scripts > @typescript-eslint/eslint-plugin > tsutils@3.21.0" has unmet peer dependency "typescript@>=2.8.0 || >= 3.2.0-dev || >= 3.3.0-dev || >= 3.4.0-dev || >= 3.5.0-dev || >= 3.6.0-dev || >= 3.6.0-beta || >= 3.7.0-dev || >= 3.7.0-beta".
warning " > slick-carousel@1.8.1" has unmet peer dependency "jquery@>=1.8.0".
[4/4] Building fresh packages...
Done in 44.34s.
Detected Next.js version: 12.0.7
Running "yarn run build"
yarn run v1.22.17
$ next build
info  - Loaded env from /vercel/path0/.env.production
Attention: Next.js now collects completely anonymous telemetry regarding usage.
This information is used to shape Next.js' roadmap and prioritize features.
You can learn more, including how to opt-out if you'd not like to participate in this anonymous program, by visiting the following URL:
https://nextjs.org/telemetry
info  - Checking validity of types...
warn  - No ESLint configuration detected. Run next lint to begin setup
info  - Creating an optimized production build...
info  - Compiled successfully
info  - Collecting page data...
info  - Generating static pages (0/4)
info  - Generating static pages (1/4)
info  - Generating static pages (2/4)
info  - Generating static pages (3/4)
info  - Generating static pages (4/4)
info  - Finalizing page optimization...
Page                                       Size     First Load JS
┌ λ /                                      17.4 kB         116 kB
├   └ css/5674832e1468d24d.css             1.14 kB
├   /_app                                  0 B            85.6 kB
├ ○ /404                                   194 B          85.8 kB
├ λ /api/orders                            0 B            85.6 kB
├ λ /api/orders/[id]                       0 B            85.6 kB
├ λ /api/products                          0 B            85.6 kB
├ λ /api/products/[id]                     0 B            85.6 kB
├ ○ /card                                  2.48 kB         104 kB
├ λ /orders/[id]                           26.3 kB         119 kB
├ ○ /payment/Paypal                        1.05 kB        96.4 kB
└ λ /product/[id]                          3.31 kB        94.8 kB
+ First Load JS shared by all              85.6 kB
  ├ chunks/framework-91d7f78b5b4003c8.js   42 kB
  ├ chunks/main-d98b4a7f39fdfc80.js        28.2 kB
  ├ chunks/pages/_app-9a201061d3b88321.js  14.6 kB
  ├ chunks/webpack-49b6f2937c9ce9f4.js     838 B
  └ css/736f475f789b4b00.css               6.93 kB
λ  (Server)  server-side renders at runtime (uses getInitialProps or getServerSideProps)
○  (Static)  automatically rendered as static HTML (uses no initial props)
Done in 21.93s.
Traced Next.js server files in: 309.973ms
Created all serverless functions in: 1.013s
Uploading build outputs...
Deploying build outputs...
Build completed. Populating build cache...
Uploading build cache [76.45 MB]...
Build cache uploaded: 1.436s
Done with "package.json"


When I check my functions logs I have this error.

[GET] /
13:39:09:78
,
      [Symbol(kCapture)]: false,
      [Symbol(RequestTimeout)]: undefined
    },
    aborted: false,
    timeoutCb: null,
    upgradeOrConnect: false,
    parser: null,
    maxHeadersCount: null,
    reusedSocket: false,
    host: 'electronic-products47.vercel.app',
    protocol: 'https:',
    _redirectable: Writable {
      _writableState: [WritableState],
      _events: [Object: null prototype],
      _eventsCount: 3,
      _maxListeners: undefined,
      _options: [Object],
      _ended: true,
      _ending: true,
      _redirectCount: 0,
      _redirects: [],
      _requestBodyLength: 0,
      _requestBodyBuffers: [],
      _onNativeResponse: [Function (anonymous)],
      _currentRequest: [Circular *1],
      _currentUrl: 'https://electronic-products47.vercel.app/api/products',
      [Symbol(kCapture)]: false
    },
    [Symbol(kCapture)]: false,
    [Symbol(kNeedDrain)]: false,
    [Symbol(corked)]: 0,
    [Symbol(kOutHeaders)]: [Object: null prototype] {
      accept: [Array],
      'user-agent': [Array],
      host: [Array]
    }
  },
  response: {
    status: 404,
    statusText: 'Not Found',
    headers: {
      date: 'Sun, 06 Feb 2022 11:39:10 GMT',
      'content-type': 'application/json',
      connection: 'close',
      'x-vercel-error': 'DEPLOYMENT_NOT_FOUND',
      'content-length': '85',
      server: 'Vercel',
      'x-vercel-id': 'iad1::gxt5k-1644147550847-622d8eef832b',
      'strict-transport-security': 'max-age=63072000; includeSubDomains; preload',
      'cache-control': 'public, max-age=0, must-revalidate',
      'x-vercel-cache': 'MISS'
    },
    config: {
      transitional: [Object],
      adapter: [Function: httpAdapter],
      transformRequest: [Array],
      transformResponse: [Array],
      timeout: 0,
      xsrfCookieName: 'XSRF-TOKEN',
      xsrfHeaderName: 'X-XSRF-TOKEN',
      maxContentLength: -1,
      maxBodyLength: -1,
      validateStatus: [Function: validateStatus],
      headers: [Object],
      method: 'get',
      url: 'https://electronic-products47.vercel.app/api/products',
      data: undefined
    },
    request: <ref *1> ClientRequest {
      _events: [Object: null prototype],
      _eventsCount: 7,
      _maxListeners: undefined,
      outputData: [],
      outputSize: 0,
      writable: true,
      destroyed: false,
      _last: true,
      chunkedEncoding: false,
      shouldKeepAlive: false,
      _defaultKeepAlive: true,
      useChunkedEncodingByDefault: false,
      sendDate: false,
      _removedConnection: false,
      _removedContLen: false,
      _removedTE: false,
      _contentLength: 0,
      _hasBody: true,
      _trailer: '',
      finished: true,
      _headerSent: true,
      socket: [TLSSocket],
      _header: 'GET /api/products HTTP/1.1\r\n' +
        'Accept: application/json, text/plain, */*\r\n' +
        'User-Agent: axios/0.25.0\r\n' +
        'Host: electronic-products47.vercel.app\r\n' +
        'Connection: close\r\n' +
        '\r\n',
      _keepAliveTimeout: 0,
      _onPendingData: [Function: noopPendingOutput],
      agent: [Agent],
      socketPath: undefined,
      method: 'GET',
      maxHeaderSize: undefined,
      insecureHTTPParser: undefined,
      path: '/api/products',
      _ended: true,
      res: [IncomingMessage],
      aborted: false,
      timeoutCb: null,
      upgradeOrConnect: false,
      parser: null,
      maxHeadersCount: null,
      reusedSocket: false,
      host: 'electronic-products47.vercel.app',
      protocol: 'https:',
      _redirectable: [Writable],
      [Symbol(kCapture)]: false,
      [Symbol(kNeedDrain)]: false,
      [Symbol(corked)]: 0,
      [Symbol(kOutHeaders)]: [Object: null prototype]
    },
    data: { error: [Object] }
  },
  isAxiosError: true,
  toJSON: [Function: toJSON],
  page: '/'
}
RequestId: 0353ce42-21d7-4ba1-80df-1a9f40898eef Error: Runtime exited with error: exit status 1
Runtime.ExitError

I have environment variables that I also added them to vercel.

MONGODB_URI= mongodb+srv://***@cluster0.ywv3z.mongodb.net/electronicProducts?retryWrites=true&w=majority
MONGODB_DB= "electronic-products47"
PROD_URL = "https://electronic-products47.vercel.app"
DEV_URL = "http://localhost:3000"

When I fetch some API by getServerSideProps I use this snippet

export async function getServerSideProps({ params }) {
  let dev = process.env.NODE_ENV !== "production";
  let { DEV_URL, PROD_URL } = process.env;
  await dbConnect();
  const res = await fetch(
    `${dev ? DEV_URL : PROD_URL}/api/products/${params.id}`
  );
  const data = await res.json();
  return { props: { product: data } };
}

I also followed this essay to host my app essay

Here my api/products route

import dbConnect from "../../../lib/mongodb";
import Products from "../../../models/Products";

export default async function handler(req, res) {
  const { method } = req;
  dbConnect();
  if (method === "GET") {
    try {
      const products = await Products.find();
      res.status(200).json(products);
    } catch (err) {
      res.status(500).json(err);
    }
  }

  if (method === "POST") {
    try {
      const product = await Products.create(req.body);
      res.status(201).json(product);
    } catch (err) {
      res.status(500).json(err);
    }
  }
}
sayinmehmet47
  • 490
  • 5
  • 21
  • 1
    Does this answer your question: [Internal API fetch with getServerSideProps? (Next.js)](https://stackoverflow.com/a/65760948/1870780)? You shouldn't be calling your internal API route from `getServerSideProps`. Instead, use the logic that's in your API route directly. – juliomalves Feb 06 '22 at 18:10
  • @juliomalves I dont think so. Because I dont have any problem with getServerSideProps in localserver. When I deploy it, I face 500 internal error – sayinmehmet47 Feb 06 '22 at 18:16
  • @juliomalves I took the same error when I was using it without refactor. So after that, I refactored it . I couldn't find any example other than the essay I share. If you have any suggestion, for using `dev ? DEV_URL : PROD_URL` in different way, I need it – sayinmehmet47 Feb 06 '22 at 18:28
  • 1
    If you refactor the code as suggested in the answer I linked, you don't fetch from the API route (no need for `DEV_URL` or `PROD_URL`). You use the code that's in the API route directly inside `getServerSideProps`. This will just work for both local development and production. – juliomalves Feb 06 '22 at 18:31
  • @juliomalves I added my api/products route. I read your link but couldn't understand how to refactor it – sayinmehmet47 Feb 06 '22 at 18:44
  • You're calling `/api/products/${params.id}` in `getServerSideProps`, so you want to import the logic that's inside the `/api/products/[id]` API route instead. Which is most likely just retrieving the product of the given ID from your database. Basically, call your database directly from inside `getServerSideProps` to retrieve whatever's needed. – juliomalves Feb 06 '22 at 18:47
  • 1
    :) it worked. I will attach the solution underneath @juliomalves. thanks – sayinmehmet47 Feb 06 '22 at 19:21

1 Answers1

1

I refactored my some components. I call my MongoDB inside serverSideProps other than calling my /api/product again

import Cards from "../components/Cards";
import CarouselComponent from "../components/Carousel";
import { Navbar } from "../components/Navbar";
import dbConnect from "../lib/mongodb";
import Products from "../models/Products";
// import "tw-elements";

export default function Home({ products }) {
  console.log(products);
  return (
    <div className="">
      <Navbar />
      <CarouselComponent />
      <Cards products={products} />
    </div>
  );
}

export async function getServerSideProps() {
  // Fetch data from external API
  await dbConnect();
  const data = await Products.find().lean();

  // Pass data to the page via props
  return {
    props: {
      products: JSON.parse(JSON.stringify(data)),
    },
  };
}

As you see I import my model Product and fetch the data directly This is the repo related https://github.com/sayinmehmet47/electronic-products47

sayinmehmet47
  • 490
  • 5
  • 21