how to fix nextjs prerender error - vercel deployment? - next.js

How do I troubleshoot this problem this deployment issue? I am following this tutorial. My node_modules and .next are ignored and not pushed to github. It works locally but can't seem to deploy. I have supplied both the component code as well as the page it's exported on. Let me know if you can see what I am missing.
https://www.youtube.com/watch?v=V4SVNleMitE
deployment errors
Error occurred prerendering page "/components/BlogPosts". Read more: https://nextjs.org/docs/messages/prerender-error
TypeError: Cannot read property 'fields' of undefined
at BlogPosts (/vercel/path0/.next/server/chunks/130.js:39:12)
at d (/vercel/path0/node_modules/react-dom/cjs/react-dom-server.node.production.min.js:33:498)
at bb (/vercel/path0/node_modules/react-dom/cjs/react-dom-server.node.production.min.js:36:16)
at a.b.render (/vercel/path0/node_modules/react-dom/cjs/react-dom-server.node.production.min.js:42:43)
at a.b.read (/vercel/path0/node_modules/react-dom/cjs/react-dom-server.node.production.min.js:41:83)
at Object.exports.renderToString (/vercel/path0/node_modules/react-dom/cjs/react-dom-server.node.production.min.js:52:138)
at Object.renderPage (/vercel/path0/node_modules/next/dist/server/render.js:673:46)
at Object.defaultGetInitialProps (/vercel/path0/node_modules/next/dist/server/render.js:315:51)
at Function.getInitialProps (/vercel/path0/.next/server/pages/_document.js:645:16)
at Object.loadGetInitialProps (/vercel/path0/node_modules/next/dist/shared/lib/utils.js:69:29)
component blog posts
export default function BlogPosts({post }) {
const {title, information,slug , thumbnail} = post.fields
return (
<div>
<div className='container w-50 h-25 mt-4'>
<Image
className='nav'
src={'https:' + thumbnail.fields.file.url}
width={thumbnail.fields.file.details.image.width}
height={thumbnail.fields.file.details.image.height}
/>
</div>
<div>
<div>
<h4 className=''>{title}</h4>
<Link href={'/contentslug/' + slug}>
<a className='btn btn-primary text-white'>Read more</a>
</Link>
</div>
</div>
</div>
)
}
Pages/Posts
import {createClient} from 'contentful'
import BlogPosts from './components/BlogPosts'
import Nav from './components/Nav'
import Logo from './components/Logo'
export async function getStaticProps() {
const client = createClient({
space: process.env.NEXT_PUBLIC_CONTENTFUL_ID,
accessToken: process.env.NEXT_PUBLIC_CONTENTFUL_TOKEN,
})
const res = await client.getEntries({content_type: 'posts'})
return {
props: {
posts: res.items ,
revalidate: 1
}
}
}
export default function Home({posts}) {
console.log(posts);
return (
<div>
<Logo/>
<Nav/>
<div className="container text-center display-5">
{posts.map(post => (
<BlogPosts key={post.sys.id} post={post}/>
))}
</div>
</div>
)
}

You have fields of undefined. this might be caused because of some strange deploying behavior if you are 100% sure your code works.
How to fix (probably):
Build your project locally. if it works, follow the next step
Comment your code in BlogPosts, inside the exported component. The code must work, so your exported component will be empty but working.
Push this code to Vercel.
Uncommit your code. (done at point 2)
Push again.
P.S. this behavior with API is sometimes caused because of API middleware you reworked.

Related

NextJs Script not rendering inside component

I am trying to implement Cookiebot on my NextJs Website.
The docs (Link to docs) mention to insert the script for the cookie declaration inside the HTML of the specific page, for me it is an own subpage only for the cookie declaration.
If I use the HTML element <script ... /> as mentioned in the docs, the text does not load when I switch to the page, but only after a refresh once I'm on the page.
If I use the NextJs Script component Link to docs by switching the <script ..> to and import it from next/script, the cookie declaration loads instantly as expected, but it is placed below everything else of the page, even under the footer (even though i wrap the pages inside a layout with footer).
My code for the layout looks like following:
`
function BasePage(props: IBasePageProps) {
return (
<div>
<Navbar />
<main>{props.children}</main>
<Footer />
</div>
);
}
This works for every page and everything - the pages are all between the Navbar and Footer. However if I use following code for the page of the screenshot, the <Script .../> text is loaded below the footer.
export default function CookieRichtlinie() {
return (
<>
<h1 className="pb-8 mt-2 text-3xl font-extrabold leading-8 tracking-tight text-gray-900 sm:text-4xl">
Cookie Richtlinie
</h1>
<div id="CookiePolicyText">
<Script
id="CookieDeclaration"
src="https://consent.cookiebot.com/12345/cd.js"
type="text/javascript"
async
/>
</div>
</>
);
`
After googling for two days I couldn't find any issue or thread close to this problem. Someone experienced this or know what I could try?
<Script ...> below everything else
Placed <Script ...> tag of next/script anywhere possible to get the loaded text inside the page. Expected to have the result of the script in the placed component, however it is always at the bottom of the page.
Did some global searches in Github and found an useEffect workaround, made some modifications and this worked in my case.
useEffect(() => {
const cookieBotWrapper = document.getElementById("CookiebotDeclaration")
if (cookieBotWrapper) {
const script = document.createElement("script")
script.id = "CookieDeclaration"
script.type = "text/javascript"
script.async = true
script.src = `https://consent.cookiebot.com/${process.env.NEXT_PUBLIC_COOKIEBOT_DOMAIN_GROUP_ID}/cd.js`
cookieBotWrapper.appendChild(script)
}
}, [])
return (
<main>
{process.env.NODE_ENV !== "development" && (
<div id="CookiebotDeclaration" />
)}
</main>
)

Nuxt3 data fetching not working after client-side navigation

I am working on a Nuxt3 app locally. I have a page component [slug].vue page component for blog posts which fetches data from a Strapi endpoint. When I navigate from the home page to a blog post via <nuxt-link> I get an empty page. When I reload the page in the browser, the data gets displayed. At this point I am kinda lost and don't know what's wrong. Here is the code of the [slug].vue
<template>
<section id="start" class="min-h-screen flex items-center">
<LayoutMoContainer is-narrow>
<div v-if="pending">
Loading ...
</div>
<div v-else>
<div v-if="post">
<AtomsMoHeadline v-if="post.title" class="text-center" headline-type="h1" :text="post.title" />
<div v-if="post.content" class="dark:text-white">
<div v-html="post.content"></div>
</div>
</div>
</div>
</LayoutMoContainer>
</section>
</template>
<script lang="ts" setup>
/**
* Fetch posts
*/
const config = useRuntimeConfig();
const STRAPI_URL = config.STRAPI_URL;
const route = useRoute();
const slug = route.params.slug;
const { pending, data: post } = await useLazyAsyncData('post', () => $fetch(`${STRAPI_URL}articles/${slug}`), { server: false });
</script>
Nuxt Project Info
- Operating System: `Darwin`
- Node Version: `v18.7.0`
- Nuxt Version: `3.0.0-rc.6`
- Package Manager: `yarn#1.22.19`
- Builder: `vite`
- User Config: `publicRuntimeConfig`, `app`, `css`, `buildModules`, `build`, `vite`
- Runtime Modules: `-`
- Build Modules: `#pinia/nuxt#0.3.1`
The problem was due to a page component having more than one root element.

Failed to compile ./styles/globals.css:4:0 Module not found: Can't resolve './${imagesat}image-hero-mobile.png'

I am getting this error in
./styles/globals.css:4:0
Module not found: Can't resolve './${imagesat}image-hero-mobile.png'
Import trace for requested module:
./styles/globals.css
./pages/_app.tsx
I am using next js as framework this error is probally due to tailwindcss .
'./${imagesat}image-hero-mobile.png' this line of code is only in one file that is
import Head from "next/head";
import Image from "next/image";
import menuList, { menuListType, menuObjectType } from "./menu";
const imagesat = "/images/01introSectionPage/";
const clients = [
"client-audiophile.svg",
"client-databiz.svg",
"client-maker.svg",
"client-meet.svg",
];
const IntroSectionDropdown = () => {
return (
<> {/* <div className="right">
<div
className={`bg-[url('${imagesat}image-hero-mobile.png')] md:bg-[url('${imagesat}image-hero-desktop.png')] h-32 w-32 bg-no-repeat bg-cover`}
>
<span className="sr-only">Hero image</span>
</div>
<img
src={`${imagesat}image-hero-desktop.png`}
alt=""
className="hidden md:block"
/>
<img
src={`${imagesat}image-hero-mobile.png`}
alt=""
className="md:hidden"
/>
</div> */}
</>
);
};
export default IntroSectionDropdown;
If i commmet the #tailwind utilities; in globals.css then website goes on but without it tailwind is not complete.
Where i used the './${imagesat}image-hero-mobile.png' is commented the also getting error.
i had tried removing tailwind and reinstalled
i had cleard the next cache
I hope anyone has solution
REPO - https://github.com/Chandraprakash-Darji/frontend-mentor-challenges

Sveltekit couldn't load and render data from Firestore

I've been trying to get this sveltekit code to work for the past 1 week and no matter how I tried, it doesn't seem to work.
Before I go to my code, this is the error message:
Cannot read properties of undefined (reading 'length') TypeError: Cannot read properties of undefined (reading 'length')
at Proxy.each (/Users/cadellteng/Documents/code/police/APDVolunteers/node_modules/svelte/internal/index.js:1710:31)
at eval (/src/lib/components/officer-list.svelte:74:29)
at eval (/src/lib/components/officer-list.svelte:109:5)
at officer-list.svelte:45:12
at Object.$$render (/Users/cadellteng/Documents/code/police/APDVolunteers/node_modules/svelte/internal/index.js:1745:22)
at eval (/src/lib/sections/training-record.svelte:25:94)
at Object.$$render (/Users/cadellteng/Documents/code/police/APDVolunteers/node_modules/svelte/internal/index.js:1745:22)
at eval (/src/routes/admin/index.svelte:17:97)
at Object.$$render (/Users/cadellteng/Documents/code/police/APDVolunteers/node_modules/svelte/internal/index.js:1745:22)
at Object.default (root.svelte:43:39)
This is my code to get data from Firebase:
<script lang="ts" context="module">
// Import Firebase
import { db } from '$lib/scripts/firebaseInit'; //from my custom FirebaseInit.ts
import { collection, getDocs } from 'firebase/firestore';
export async function load() {
let allOfficers = [];
console.log("Loading data");
const querySnapshot = await getDocs(collection(db, "officers"));
// console.log(querySnapshot);
querySnapshot.forEach((doc) => {
// doc.data() is never undefined for query doc snapshots
let data = doc.data();
// console.log(doc.id, " => ", data);
allOfficers.push(data);
});
console.log(allOfficers)
return {
props: { allOfficers }
};
}
</script>
<script lang="ts">
export let allOfficers;
</script>
And the following are my code to render the data:
<div class="officer__list">
{#each allOfficers as officer}
<div class="officer__card accordion">
<div class="officer__content-details">
<h4 class="officer-name">{officer.name.displayed}</h4>
<p class="officer-rank-appointment">
Rank 1 | Head of Department
</p>
</div>
</div>
{/each}
</div>
And just in case you are wondering if my FirebaseInit.ts is not working well, I have another example that worked without changing anything in the script tags:
<div class="test-container">
<ul>
{#each allOfficers as officer}
<li>
{officer.name.displayed}
</li>
{/each}
</ul>
</div>
The above works like magic without changing anything in the script tags.
Edit: This is a component within a bigger svelte file. I realize when I make this its own route, it works...? What's wrong?
So I have managed to solve the problem and I can't use the context module to load data at the component level. After I move the script tag content for the load to the route level, it works perfectly. I just need to pass it down into individual components as props.

Meteor, Flow Router, and React: How to get FlowRouter.subsReady() function to be reactive in render

I am trying to create a pattern so that all the subscriptions are ready before I load the main page. Similar to Iron Router waitOn.
Take a look at this react component:
export const PageContainer = React.createClass({
render() {
return (
<div id="content-box">
<div className="banner banner-primary">
<div className="page_title pull-left">
{this.props.pageName}
</div>
</div>
<div>
{ FlowRouter.subsReady() ? this.props.page : (
<div> Loading .... </div>
)
}
</div>
</div>
);
}
});
as you can see I am using the FlowRouter.subsReady() helper to render the page or the loading text.
The problem is that this is not reactive. It just renders once but does not update and show the page once the subscription is ready.
How can I get this to be reactive?
What is the best way to use Flow Router's subscription management with React. I have a base layout and want to show loading sign before loading the page main. If I could get this function to be reactive it should work just fine.
UPDATE:
It seems like I have to attach the helper, FlowRouter.subsReady() to the get Meteor data function
export const PageContainer = React.createClass({
mixins: [ ReactMeteorData ],
getMeteorData() {
return {
isLoading: FlowRouter.subsReady()
}
},
render() {
return (
<div id="content-box">
<div className="banner banner-primary">
<div className="page_title pull-left">
{this.props.pageName}
</div>
<i className="fa fa-question-circle help-icon pull-right"></i>
</div>
<div>
{ this.data.isLoading ? this.props.page : (
<div> Loading ... </div>
)
}
</div>
</div>
);
}
});
It seems to be working now. Is this the way to do it?
You accessed the problem in the wrong direction. You don't really need to check the subsReady of FlowRouter when using meteor with react. Just install the mixin ReactMeteorData and set the this.data properly, it will reactively render the Dom. More details here
React render is not reactive. The Dom is only re-rendered when the props or state of the component is changed

Resources