Next.js, getStaticProps not working with component but does with page

getStaticProps works only for page components inside pages folder. And the data is fetched at build time. Here is what the documentation says: getStaticProps can only be exported from a page. You cannot export it from non-page files, _app, _document, or _error. If you wanna use UserTransactionsComponent as a normal component, you should use useEffect … Read more

Want to have an event handler for the browser’s back button with next.js

You can use next/router‘s beforePopState to act on changes to the session history navigation (back/forward actions), and make sure it’ll only happen when leaving the current page. useEffect(() => { router.beforePopState(({ as }) => { if (as !== router.asPath) { // Will run when leaving the current page; on back/forward actions // Add your logic … Read more

Next Image not taking class properties

Before Next.js 12.2 Styling the next/image component’s margins this way doesn’t work in older Next.js versions. See relevant GitHub discussion for more details. Internally to the next/image component, the <img> element and the elements that wrap it have inline styles that override certain values passed through className. As a workaround, you can add a wrapper … Read more

How to fetch data server-side in the app directory of Next.js? Tried getStaticProps but it’s returning undefined

Methods like getServerSideProps and getStaticProps are for fetching data on the server but they only work for page components inside the pages folder (the initial way of setting up routes in Next.js). Since Next.js 13, in the app directory we have Server Components, where you can fetch data directly in the component body. In your … Read more

How to avoid caching in the app directory of Next.js?

Yes, in the app folder, Next.js by default caches all fetched results. If you are using fetch(), you can change this behavior per query, with revalidate or cache option: fetch(‘https://…’, { next: { revalidate: 10 } }); fetch(‘https://…’, { cache: ‘no-store’ }); You can also control the behavior with Route Segment Config, again if you … Read more

Next.js app folder: is there some “entry point”? A direct replacement for _app.tsx?

On the Upgrade Guide page, they say “pages/_app.js and pages/_document.js have been replaced with a single app/layout.js root layout”. So in your case, you can put your logic there and make it a client component with “use client” at the top if you want client interactivities like a useEffect in it. But say you don’t … Read more