Next.js Discord

Discord Forum

Nextjs running in dev works as expected but in Production does not

Unanswered
Yellow croaker posted this in #help-forum
Open in Discord
Yellow croakerOP
So when I run the command npm run dev my code works exactly the way I want it to, but when I deploy, it does not show a modal that shows on the localhost, so basically the stuff that works on dev does not work once deployed

111 Replies

You are going to have to be alot more descriptive than that.... We need code, and are you using app router or pages router?
@Yellow croaker
Yellow croakerOP
// src/app/page.js
import JobBoard from "@/app/components/jobs/jobBoard";
import { fetchVacancies } from "./functions/fetchVacancies";

// Server Component
export default async function Page() {
  const data = await fetchVacancies();

  const generatedHtmlContents = data
    .map((row) => {
      const datePosted = new Date(row.meta.createdDate.seconds * 1000)
        .toISOString()
        .split("T")[0];
      const validThrough = new Date(row.details.expiryDate.seconds * 1000)
        .toISOString()
        .split("T")[0];

      const jobPostingSchema = {
        "@context": "https://schema.org",
        "@type": "JobPosting",
        title: row.details.position,
        description: row.details.description,
        industry: row.details.industry,
        datePosted,
        validThrough,
        employmentType: row.details.employmentType,
        hiringOrganization: {
          "@type": "Organization",
          name: row.company.name,
        },
        jobLocation: {
          "@type": "Place",
          address: {
            "@type": "PostalAddress",
            addressRegion1: row.location?.addressRegion1,
            addressLocality: row.location?.addressLocality,
            addressRegion: row.location?.addressRegion,
            addressRegion2: row.location?.addressRegion2,
            addressCountry: row.location?.addressCountry,
          },
        },
        baseSalary: {
          "@type": "MonetaryAmount",
          currency: row.details.currency || "ZAR",
          value: {
            "@type": "QuantitativeValue",
            unitText: "PER MONTH",
            value: row.details.salary,
          },
        },
      };

      return `
      <div>
        <script type="application/ld+json">
          ${JSON.stringify(jobPostingSchema)}
        </script>
      </div>
    `;
    })
    .join("");

  return (
    <>
      <div dangerouslySetInnerHTML={{ __html: generatedHtmlContents }} />
      <JobBoard vacancies={data} />
    </>
  );
}
so that data from fetchVacancies does not update on page refresh when deployed
but in dev it gets the updated data, so lets say i add an entry to the DB and reload the page in dev the new data shows, when deployed it doesnt
also the icon does not show when deployed but dev does
Not sure about the icon but humor me and try this


import {unstable_cache} from 'next/cache';

const data = await unstable_cache(fetchVacancies, [], {revalidate: 60})()
Yellow croakerOP
trying it now thanks so this updates every min ?
Yeah
of course you could change that
but just give it a shot for me and see what happens
Yellow croakerOP
i dont know much about nextJS so thank you
You dont this project for school or something?
Yellow croakerOP
no
just never used next js before
Gotcha
Yellow croakerOP
just waiting to see if it changes now
np
If that doesnt work we are going to have to look at the fetchVacancies function
Yellow croakerOP
its not updating
import { db } from "@/app/api/firebase"; // Adjust the path as necessary
import { collection, query, where, getDocs } from "firebase/firestore";

export async function fetchVacancies() {
  try {
    const vacanciesQuery = query(
      collection(db, "vacancies"),
      where("status", "==", "Active")
    );

    const snapshot = await getDocs(vacanciesQuery);

    const vacancies = snapshot.docs
      .map((doc) => ({
        ...doc.data(),
        id: doc.id,
      }))
      .filter(
        (vacancy) =>
          typeof vacancy.details.location === "object" &&
          !Object.values(vacancy.details.location).some(
            (value) => value === ""
          ) &&
          vacancy.details.rateType
      );

    vacancies.sort((a, b) => b.meta.createdDate - a.meta.createdDate);

    return vacancies;
  } catch (error) {
    console.error("Error fetching vacancies:", error);
    return []; // Return an empty array in case of an error
  }
}
this is fine if it was react only this would work 100%
Are you deploying with npm run build then npm run start?
Yellow croakerOP
in a useEffect
npm run build yes and its on firebase so im pretty sure it uses npm run start or npm start
You can see the logs when its started right?
Im assuming?
When you run npm run build can you show me what this looks like?
Yellow croakerOP
I can check but iv never seen logs for firebase
Need to see if its showing up as static
Yellow croakerOP
yes it does that
sec
your '/' route is where the page your using is?
Thats the only page it sees so im assuming so?
Yellow croakerOP
yes
so the issue is its generating it as static which is weird
f is dynamic. hrmmmm
Yellow croakerOP
i need the html i add to be there on page load
but if i use a client side it doesnt register the js on crawlers
gotcha, one sec.
add
//Top of file
import { cookies } from 'next/headers'


//In page
const cookieStore = cookies()
to your page.js
then rebuild and show me the build log
Should force it to be dynamic.... should, but just trying to isolate the issue
Yellow croakerOP
gotcha
OKay looking good. now try starting it and see if it updates
Yellow croakerOP
deploying now
In theory you can remove unstable cache now if you want, itll fetch every page load, or you can keep the cache and itll only update every 60 seconds
but it is weird that nextjs build is not detecting it as dynamic without forcing it by accessing cookies or what have you
Yellow croakerOP
thats what i get now
lol.... hrmmm
this has to be a firebase thing.... ive never used it, does it only allow for static content?
Yellow croakerOP
no
its a service like amazon or azure
they have thier own no SQL db among other things
but hosting is web app hosting
I gotcha, hrmmmm.
Yellow croakerOP
if i remove the cookies goes back
Oh okay, so it was a browser issue
is it updating now?
Yellow croakerOP
no i mean the code
Ohhhh, sorry.
but now when you build its static again
Yellow croakerOP
yes
static = generate at build but never again
dynamic = generate at request for page
which is the only thing the cookies call was doing
Yellow croakerOP
OH that makes sense
Still dont know why its not working when its dynamic
Yellow croakerOP
im aslo quite confused
I dont know anything about firebase :/
Yellow croakerOP
i see
export option ?
It wont work, because it would be static.
Yellow croakerOP
so i cant host on firebase'
?
I think you can... but you would have to fetch using cloud functions on the page, instead of directly fetching from the database.
https://firebase.google.com/docs/hosting#:~:text=Beyond%20serving%20static%20content%2C%20you,your%20changes%20before%20going%20live.
Yellow croakerOP
thats no issue
iv made quite a few cloud functions
I understand that its no issue, I just dont know how it works because ive never used firebase.
You essentially have to decouple the fetch logic from your nextjs app and fetch from the cloud function instead of inside of nextjs
Yellow croakerOP
yeah im also not sure why that makes a change
maybe it forces the cloud function to run and therefore makes the data update
but it would still need to be dynamic
Yeah, well as far as nextjs is concerned it would be static if the fetching was done on the client side I think?
because it ships the fetch logic to the client
Yellow croakerOP
but i cant do that
so I think it has to be client side fetching to work in firebase.
I know
Yellow croakerOP
as the crawlers wont get data
I understand.
I just dont see another way
Yellow croakerOP
So iv been in a logic conundrum
If you were hosting on say vercel, this wouldnt be an issue (I understand not wanting to host on vercel though)
I just dont know the answer, if there even is one lol
Yellow croakerOP
im in the same boat
i could use vercel
if this was on vercel you wouldnt have this issue at all, they have a hobby plan.
Yellow croakerOP
Okay ill set that up and check back in with you
Yellow croakerOP
@Jboncz vercel fixed alot of the other issues i had like the icon and modals not showing
Yellow croakerOP
could you help me with one last issue
where the table ends with data it just keeps going
and page 2 looks like this
where its cut off is the end of the html
if i inspect in dev tools