2

I'm developing a website for a college class, followed a tutorial on YouTube since I have no real experience with this level of coding. The site "works" locally...when I execute it, at first the screen is just white, but if I refresh the page it comes up, and everything functions (it's a pizza website, the products and ordering and everything works locally). But, when I inspect while the screen is white, I see that I'm getting an internal server error:

enter image description here

enter image description here

I believe the issue is somewhere in my api/products/index file, but I'm not sure

Here is the code for that file:

import dbConnect from "../../../utilities/mongo"
import Product from "../../../models/Product"

export default async function handler(req, res) {
    const {method, cookies} = req;

    const token = cookies.token

    dbConnect()

    if(method === "GET"){
        try {
            const product = await Product.find();
            res.status(200).json(product);
        } catch (err) {
            res.status(500).json(err)
        }
        }

    if(method === "POST"){
        if(!token || token !== process.env.TOKEN){
            return res.status(401).json("Not Authorized")
        }
        try{
            const product = await Product.create(req.body);
            res.status(201).json(product)
        }catch(err){
            res.status(500).json(err);
        }
    }
  }

Here is a link to my github with all code: https://github.com/InvisibleH3R0/mellowyellowpizzaria

Any assistance on what is wrong would be highly appreciated!

EDIT: Here are screenshots of my terminal: enter image description here enter image description here enter image description here enter image description here enter image description here

Chris Johnson
  • 69
  • 1
  • 2
  • 8
  • 1
    Could you clarify the error? The error 500 is a client-side error that shows on your browser and error 500 typically means something has gone wrong on the server end. If you can open up the terminal where you are running the development server, you should see a more detailed error explanation. Would you mind sharing that here so we can assist you further? – angol Jul 10 '22 at 00:08
  • 1
    Upon analysis of your code, I can see that your DB information is in your Git repo. I advise you urgently to add .env to your .gitignore to avoid anyone maliciously abusing your database credentials! – angol Jul 10 '22 at 00:13
  • Ah, I thought that was in my .gitignore, haha, I'll fix that, thank you :) I mean, this is just a school project, so I'm not overly concerned, but yeah, good practice...give me a few and I'll post screenshots from my terminal, it's a lot – Chris Johnson Jul 10 '22 at 00:33
  • [Don't show pictures of text, show the text](/help/how-to-ask). But, also only show the _relevant_ text. A request or response dump is not useful, whereas a [mcve] is: reduce your code to _just_ something that sets up the server, sets up the `/` route, and then see if you still get the error. If not: cool, start building that back out until you either run into the error again (in which case you know what's causing it) or you don't (in which case there's no problem to solve =) – Mike 'Pomax' Kamermans Jul 10 '22 at 00:47
  • I gotcha, yeah I'm crazy new to this level of coding/development...not even sure why this is my capstone class, I'm a Cyber Security major, lol...anyways, that being said, I don't know what the relevant text is here, so I just posted it all. As far as the minimal reproducible example...I'll work on that, but again, my skills here are basically non-existent, all of this code I basically wrote just following a YouTube video, so yeah...but thank you, I will play around with it and see if I can get it to a point where it works, then slowly add back from there – Chris Johnson Jul 10 '22 at 01:07
  • 1
    Looking at your repo, I can see you are calling your API endpoint inside your `getServerSideProps` function in your `index.js` page. You should be writing your DB logic inside `getServerSideProps` directly since calling your endpoint in this function is considered bad practice. You can read more about this [here](https://nextjs.org/docs/basic-features/data-fetching/get-server-side-props) – ivanatias Jul 10 '22 at 01:47
  • I get what you're saying, I think, but I'm also confused because the section "Using getServerSideProps to fetch data at request time" is basically how I have my code written. When you say my DB logic, I will be honest, I'm not exactly sure what you mean :/ Like I said, I'm crazy new to this, and honestly probably won't do anything else like this outside of this class, lol, I'm just trying to pass so I can graduate...but this has been a 'fun' learning experience so far and I do appreciate yall's assistance with this – Chris Johnson Jul 10 '22 at 01:59
  • 1
    What I mean is, the whole point of an API endpoint is to run certain code only on server-side but since `getServerSideProps` never executes on the client-side, it's unnecessary to call your API endpoint in there. From Next.js docs: "This is an unnecessary and inefficient approach, as it will cause an extra request to be made due to both getServerSideProps and API Routes running on the server." – ivanatias Jul 10 '22 at 02:04
  • Gotcha, and yeah I read that part as well...but I'm not sure how to fix it? What do I put in there instead to get the data from my product code? And it's odd they say it's "unnecessary...." but then show it in an example...? – Chris Johnson Jul 10 '22 at 02:09
  • You should write the GET request logic to your DB directly in `getServerSideProps`. In more simple words, the logic that requests your products data. – ivanatias Jul 10 '22 at 02:12
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/246304/discussion-between-chris-johnson-and-ivanatias). – Chris Johnson Jul 10 '22 at 02:16

1 Answers1

1

Looking at your repo, I can see you are calling your API endpoint inside your getServerSideProps function in your index.js page. You should be writing your DB logic inside getServerSideProps directly since calling your endpoint in this function is considered inefficient and could give you some problems. You can read more about this here.

Try this:

export const getServerSideProps = async (ctx) => {
  const myCookie = ctx.req?.cookies || "";
  let admin = false;
  if (myCookie.token === process.env.TOKEN) {
    admin = true;
  }
  await dbConnect();
  const res = await Product.find();
  return {
    props: {
      pizzaList: JSON.parse(JSON.stringify(res)),
      admin,
    },
  };
};
ivanatias
  • 3,105
  • 2
  • 14
  • 25