How to debug getStaticProps (and getStaticPaths) in Next.js - reactjs

I am trying to debug the getStaticProps() method of a React component included from my pages using console.log() like:
export default class Nav extends React.Component {
render() {
return <nav></nav>;
}
async getStaticProps() {
console.log('i like output, though');
}
}
However, I am neither able to see any output on the console from which the app is being served, nor on the browser's console. I also tried restarting yarn dev and running yarn build to see if it would produce output then. Alas, no cigar.
So what is the correct way to produce and read debug output from getStaticProps() and getStaticPaths()?

So after further research and testing I found out that getStaticProps() is only called on page components. So that was why I wasn't seeing any output. When I added the method to a component inside the pages directory I was able to see debug output produced with console.log() in the console running yarn dev on manual browser page refreshes (but not on automatic refreshes after modifying the page component) as well as during yarn build.

You can easily debug server-side code of your next application.
To enable it you need to pass NODE_OPTIONS='--inspect' to your node processor. Best place to put it is in your package.json file where you run the app in dev mode => "dev": "NODE_OPTIONS='--inspect' next dev" .
Now open a new tab in your chrome browser, and visit chrome://inspect. This will open chrome dev tool inspect where you can see your nextJs server under Remote Targets, Just click ìnspect. By clicking that it will open a new inspect window.
Now simply put debugger inside your getStaticProps function and reload your client app, you will see the breakpoint in your server side code.
I hope this helps.
Reference: https://nextjs.org/docs/advanced-features/debugging#server-side-code

getStaticProps runs on the server-side and not on the client-side.
getStaticProps only runs on the server-side. It will never run on the client-side. It won’t even be included in the JS bundle for the browser.
Ref: https://nextjs.org/learn/basics/data-fetching/getstaticprops-details

Using the current next version (11.x) you can use console.log to print out any data in the getStaticProps() function.
You will see that output in the terminal where you run
vercel dev

Your console.log will work but in the console of your app Terminal, not in the console in the browser. There you can check your message.
Also, if you get data [Object] then just in that console, make JSON.stringify(yourValue).
if it's a bigger object than stringify you can write like JSON.stringify(yourValue, null, 2) and it will be displayed within JSON way.

Related

NextAuth.js for authentication with Google facing [client_fetch_error] with next.js

I am using the next-auth.js library for authentication with Google in next.js. It is working fine in the localhost but I'm facing the issue in the Production environment. I went through the next-auth documentation and I found out it is a known issue with the environmental variables.
The error which I am facing is: [error][client_fetch_error] https://next-auth.js.org/errors#client_fetch_error. So I made changes in the code by adding an environmental variable which is NEXTAUTH_URL = "https://domainname/" as they mentioned in the documentation. Still, I am facing the same error also it is throwing a bad gateway request GET https://domaniname/api/auth/session 502 . Also, I ensured that the clientId, clientSecret are having the correct values and the Authorized redirect URIs: https://domainname/api/auth/callback/google
Could anyone help me out on how to rectify it?
You are facing this issue because you are trying to add dynamic API routing to a static website.
The documentation has a pretty good explanation of this.
Why This Warning Occurred
An exportPathMap path was matched to an API route. Statically exporting a Next.js application via next export disables API routes.
Now, it's likely you didn't set an exportPathMap directly (though you can do that in next.config.js). More likely, you are building your application with an extra export command in your build script in package.json - this is what is triggering the warning.
There is some more explanation on this in the Static HTML Export section:
API Routes are not supported by this method because they can't be prerendered to HTML.
... and in the API Routes section.
API Routes can't be used with next export
Okay, but how do I fix this?
The way to fix this is to make your application non-static (SSR or SSG). The easiest way to do this is to remove the export command, and add a start.
Package.json:
"scripts": {
"build": "next build",
"start": "next start"
}
You need to make sure that the start command is run - this might differ depending on your host.

React app showing blank page in GitHub pages

After uploading my react app on gitHub pages its showing a blank page, and there is no error displaying in console. When I inspected the pages it says:
You need to enable javascript to run this page
but when I checked by browser settings it shows my javascript is enabled.
Here is my console
Here are the elements
Here is the Package.json
Also when I tested with a basic react app(no routes only single page) it was displaying properly
If gitHub is not publishing, is there any other alternative to publish my work?
Thanks
It looks good from my side. You should try with another browser to see if the problem persists.

Nextjs 404 error on reload/ refresh action

I'm using Nextjs for a front-end application and dotnet core 3.1 for the Web API. There are some pages that are static and other that are dynamic I followed the official documentation to achieve this. On development mode (local machine) everything works fine. Both static and dynamic routes are working properly and fetching data from the dontnet core Web API.
However, when publishing the Nextjs app following this steps:
yarn build
yarn export
An out folder is generated at the root of the project
The content of that folder is uploaded to the server
After, the deployed files are uploaded and when loging to the app, it redirects to the main page (until here is working OK), but as soon as I click on the reload page botton (Chrome) I am gettint the 404 error.
Looking at the console in the developer tools I got this:
I found this Stackoverflow link with same issue but there the answer is to use Express for server routing. In my case I am using dotnet core Web API for server requests. So, not sure how to do that.
Is there a way to fix this from the client side? Might be a configuration is missing?
The only thing I noticed while doing the export was a message saying: No "exportPathMap" found. Not sure if that would the the reason.
I had got similar issue in react when all of my pages after building and exporting had ".html" extensions. I solved it by the following code in next.config.js file.
next.config.js
module.exports = {
exportTrailingSlash: true,
}
Note: Do not work with the above code while in development. Use it just before building the project.
You can find the documentation link here: https://nextjs.org/docs/api-reference/next.config.js/exportPathMap#adding-a-trailing-slash.
UPDATE
The above code was for next.js v9.3.4 which I was using at that time. For newer versions below code should be used according to docs.
next.config.js
module.exports = {
trailingSlash: true,
}
it has been fixed update your nextjs package
npm install next#latest
based on the current version of Next js you have, visit here to see if there's any breaking change before updating what you have
I had a similar issue where after deploying the out folder created by next export all URL's would redirect me to the homepage. Everything was working fine during development and all URL's were accessible with next/link but in order to access pages with a URL I had to add a .html extension at the end of the URL.
Because I needed a quick workaround I added a useEffect block in the _app.tsx file for rerouting so that upon landing on the homepage it would act as if a Link component was clicked redirecting to the entered URL.
useEffect(()=>{
router.push(window.location.href)
},[])

Locally accessed react app does not do API call [CRA]

I am using CRA to setup my react app.
I want to ask, how do I make a locally accessed react app do API call.
To explain my question, I can only do it by describing it.
So currently, my machine has 192.168.1.2 as its IP.
My backend server is running on 192.168.1.2:3000 (if i hit 192.168.1.2:3000/customers on browser I get the json response)
My frontend is running on 192.168.1.2:3001
If i open http://localhost:3001 or http://192.168.1.2:3001 from my laptop browser, all components render, it will render the Loading component and then not long after the list will render. (If i check my backend server, i can see that my server receives GET request)
However if I open http://192.168.1.2:3001 from my phone, all components render, but it is stuck at Loading component. When I check my backend server, it receives no request at all. So from what I can see is that by accessing my react app locally outside from the hosting machine, the app won't do any API call.
How do I fix this?
Things I have done:
Adding "proxy": "http://localhost:3000" and "proxy": "192.168.1.2:3000" to package.json (both doesn't work)
Changing "start" script to: "HOST=0.0.0.0 react-scripts start" and "react-scripts start --host=0.0.0.0" (both does not work)
My best guess is that you are fetching from localhost similar to this:
fetch("http://localhost:3000/customers")
The reason proxy isn't working in the config file would be because you need to remove "http://localhost:3000" from the fetch. Otherwise, it is still pinging localhost for the api, and not using the proxy setting. So it should look like this:
fetch("/customers")
Of course, without a reproducible example, it is hard to tell if that is exactly the problem you are having.

React not fetching data from the updated env file

There are some environment variables in my .env file that gets updated when some values get updated on the database.
Example:
REACT_APP_FIREBASE_ID=1234567890
When I log this to the console on my react app:
console.log(process.env.REACT_APP_FIREBASE_ID) //this gives "1234567890"
But when the .env file is updated with something else:
Example:
REACT_APP_FIREBASE_ID=9876543210
The log still gives the old value:
console.log(process.env.REACT_APP_FIREBASE_ID) //this still gives "1234567890"
I am using on CRA on dev mode with "npm start"
If I terminate the server and restart it again, I am able to see the correct output to the console.
BUT, this doesn't work after "npm run build"
How can I clear the environment cache after the .env file is changed on the Production Mode?
This is how I solved it.
My first approach was to get the value from the .env file, but unless the server is restarted, this approach doesn't work. [BAD]
My second thought was to create a JSON file and keep the data from inside that, and update the JSON file whenever the Database is updated.
Sadly, this was a very bad approach because CRA (or probably any react project) cannot call a file outside the src folder and after the build, there is no scope to change the built js files. [VERY BAD]
Finally, I managed to solve this using this approach [DECENT, I Guess]
Saving the data on a table in a key-value format (You may just save in JSON format too)
When the application is loaded (main component is loaded), call an API that gets that key-value(or JSON) and store the data in the LocalStorage of the browser.
Get the value on the application with localStorage.getItem("theKeyName")
A Tip:
You could check if the key is already present on the LocalStorage before making the API call.
if(localStorage.getItem("theKeyName") !== null) {
//your API fetch request or redux dispatch
}

Resources