Nextjs deployed on Vercel = blank page - reactjs

I managed to deploy my Nextjs app (whith getStaticProps + i18n + firebase) on Vercel.
But i get a blank screen.
Here's the log:
Status: 200
Duration: 8.18ms
Memory Used: 111 MB
I tried :
Checking the build function locally: it works perfectly.
Changing the default build and development settings to these (with no luck) :
I even tried to deploy on netlify (even thought i don't think they support i18n because i18n doesn't support next export), but i get a 404 page, which is the equivalent of a blank page in Vercel.
I also tried:
Creating a new git and re-deploying. But I still get an empty result after a perfect deploy with a list of all my pages and stuff...
Deleting i18n.
Deleting index.html from public
Deleting all pages but one.
Deleting _document.jsx
Deleting every public folder pages except assets like images.
Deleting package lock file.
Stil nothing works.
And yet, i get a perfect previw of my webapp in Vercel, but the link goes to a blank page.
Any idea?

My mistake.
It was a problem with my getServerSideProps code
To this :
export async function getServerSideProps({ req, res }) {
const data = cookie.parse(req ? req.headers.cookie || "" : document.cookie);
if (res) {
if (Object.keys(data).length === 0 && data.constructor === Object) {
res.end();
}
}
return {
props: { userId: data.userId }, // will be passed to the page component as props
};
}
I went to this:
export async function getServerSideProps({ req, res }) {
const data = cookie.parse(req ? req.headers.cookie || "" : document.cookie);
return {
props: { userId: data.userId }, // will be passed to the page component as props
};
}
The res.end(); was the problem.

Deleting the following worked for me:
"homepage": "https://your-username.github.io/the-repo-project/",
vercel --prod
You have to wait a minute
But I think it depends on the project.

I ran into the same issue of having a blank page. I later discovered that I was running "npm run dev" in the wrong directory.
Instead of cd C:\wamp\www\projectname, I typed cd c:\wamp\www\projectname.
The difference is capital letter "C". Small letter "c" won't work.
Ensure your casing (capital or small) is right and everything spelt correctly. Then, run "npm run dev" and see your expected page display (if there are no other errors hindering it from showing).

Related

Nextjs 12 Error When Running on Cloud Run But Works Well on Localhost

I'm trying to upgrade from nextjs v10 to v12. It successfully worked at localhost, but when deployed on cloud run and running on the active domain, it shows 500 Internal Server Error. Previously it worked well on cloud run with nextjs v10.
I create a test page to check what makes it error and after testing, it may seems the 'getServerSideProps' is the problem.
Here is my code, /pages/test2.js
import Layout from 'components/layout'
export async function getServerSideProps({ req, res }) {
return {
props: {
data: { title: 'test' },
},
}
}
export default function Test({ data }) {
console.log('testtt', data)
return (
<Layout activeId="home">
<div>ABC TEsT</div>
</Layout>
)
}
If I remove 'getServerSideProps' function then deploy to cloud run, then the page is working well.
Here is the error found on cloud run server log
SyntaxError : Unexpected token '.'
Link to error image
The weird thing is, there is no error on localhost.
Is there any problem with getServerSideProps on nextjs v12 or I am missing configuration?
I have no custom webpack and babel config.
Thank you

Nextjs API works in local environment but not in production environment

[SOLVED]
I have created a dynamic API route in NextJS that, if given a filename, the server will read the file (.md or .txt file) under the content directory, convert it into string and returns it. The API works as intended in local environment, however, the deployed website in Vercel doesn't work properly for this API route.
That API route, for a file that exists in the content directory, returns 500 internal server error.
The console error is:
Failed to load resource: the server responded with a status of 500 ()
Checking the vercel logs for the route, showed this:
ERROR Error: ENOENT: no such file or directory, open 'content/phase1_section1.md'
I think the path.join() is not working for me. It is not adding the actual domain name of the app in front of the content part. How can I resolve this?
And, here's the code
import { readFileSync } from 'fs';
import path from "path";
export default function courseHandler({ query: { slug } }, res) {
const fullPath = path.join('./content/', slug);
const content = readFileSync(fullPath, 'utf8');
if (content) {
res.status(200).json({
content: content
});
} else {
res.status(404).json({ message: `Course with slug: ${slug} not found.` })
}
}
The problem is actually solved.
I just replaced this
path.join('./content/', slug);
with this
path.join(process.cwd(), 'content', slug);
Check logs on Vercel
Configure yours .env variables on Vercel for each environment
Check your local .env files. if you hardcoded your .env variables - this will cause a negative impact.

Netlify deployment Cannot query field "allContentfulGallery" on type "Query"

I am creating an application on React.js, Gatsby.js, and Contentful. My Application is working fine on my local but when I deploy my app to Natilify Cannot query field "allContentfulGallery" on type "Query". And My GraphQl Queries are also working fine. Please help me I am very sticking by this error."allContentfulGallery" is my collection Name
Very thanks in advance
My gatsby-node.js configuration
const galleryResult = await graphql(`
query gallery {
allContentfulGallery {
edges {
node {
title
slug
images {
title
file {
url
}
}
sys {
contentType {
sys {
id
linkType
type
}
}
revision
type
}
}
}
}
}
`)
var galleryArr =
galleryResult &&
galleryResult.data &&
galleryResult.data.allContentfulGallery &&
galleryResult.data.allContentfulGallery.edges
galleryArr.forEach(edge => {
createPage({
path: `/gallery/${edge.node.slug}`,
component: galleryTemplate,
context: {
title: edge.node.title,
slug: edge.node.slug,
sys: {
...edge.node.sys,
},
},
})
})
It seems (according to the comments) that the environment variables are not properly set, since they work locally (under both environments, gatsby develop and gatsby build) but not on GitLab nor Netlify.
Dealing with Gatsby + Netlify requires to prefix all environment variables with GATSBY_ as you can see in Netlify docs:
Any environment variables prefixed with GATSBY_ are processed by
Gatsby and made available in the browser for client-side JavaScript
access. Visit the Gatsby docs about environment variables for more
information.
So, change all variables locally, and in Netlify's and GitLab dashboard prefixing them with GATSBY_.
CONTENTFUL_ENVIRONMENT
CONTENTFUL_API_KEY
CONTENTFUL_SPACE_ID
Will become:
GATSBY_CONTENTFUL_ENVIRONMENT
GATSBY_CONTENTFUL_API_KEY
GATSBY_CONTENTFUL_SPACE_ID
Keep in mind that this approach applies to all environment variables, not only for the Contentful ones.
Normally I'm pretty sure about the resolutions but in your case, if you haven't set the environment variables properly, the plugin configuration should fail, breaking the compilation before your issue prompts and it's not the case.

Next JS dynamic routing not working on export production static build

I'm building an app with Next. using nested dynamic routing. In development mode, everything works as expected. But when I deploy the app in production ,When you hit reload (like F5) it gives you 404
use next version : 9.5.2
my directory structure is like this:
pages
-users
-[page]
- [id].tsx
- index.tsx
-index.tsx
Here's how I link to the dynamic page:
<Link href='/users/[page]/[id]' as='/users/edit/${id}'>
<a>Edit</a> </Link>
Here sample code user/[page]/[id].tsx
class User extends React.Component {
constructor(props) {
super(props);
this.state = {
},
};
static getInitialProps({query}) {
return {query}
}
async componentDidMount(){
const { query } = this.props;
if(query?.id){
await this.props.getUserById(query?.id);
}
}
}
Here static build command
`npm run export`
Here static build
my build is a set of HTML, js, css assets I hosted on the web server (Apache, Nginx).
If I clicked in link users from index.tsx page, my URL look '/users/edit/1/' and work fine, but if I refresh the page I get error 404. In the development mode refresh page, everything works fine.
I am stuck on this problem for many days. Do u know how I can fix this?

How to check if asset was added from public/ dir in React?

Is it possible to check if a file exists within the /public/ directory?
I have a set of images that correspond to some objects. When available, I would like to display them using <img> tag. However not all of the objects have a corresponding image, in which case I would like to perform a REST request to our server.
I could create a list of files as part of build process, but I would like to avoid that if possible.
I am using create-react-app if it matters (if I understand correctly fs doesn't work in client-side React apps).
EDIT: I guess I should have been more exact in my question - I know client-side JS can't access this information (except through HTTP requests), I was just hoping something saves information (during build) about the files available in a way that is accessible to client-side Javascript... Maybe Webpack or some extension can do this?
You can do this with your axios by setting relative path to the corresponding images folder. I have done this for getting a json file. You can try the same method for an image file, you may refer these examples
Note: if you have already set an axios instance with baseurl as a server in different domain, you will have to use the full path of the static file server where you deploy the web application.
axios.get('http://localhost:3000/assets/samplepic.png').then((response) => {
console.log(response)
}).catch((error) => {
console.log(error)
})
If the image is found the response will be 200 and if not, it will be 404.
Edit: Also, if the image file is present in assets folder inside src, you can do a require, get the path and do the above call with that path.
var SampleImagePath = require('./assets/samplepic.png');
axios.get(SampleImagePath).then(...)
First of all you should remember about client-server architecture of any web app. If you are using create-react-app you are serving your app via webpack-dev-server. So you should think about how you will host your files for production. Most common ways are:
apache2 / nginx
nodejs
but there is a lot of other ways depending on your stack.
With webpack-dev-server and in case you will use apache2 / nginx and if they would be configured to allow direct file access - it is possible to make direct requests to files. For example your files in public path so
class MyImage extends React.Component {
constructor (props) {
super(props);
this.state = {
isExist: null
}
}
componentDidMount() {
fetch(MY_HOST + '/public/' + this.props.MY_IMAGE_NAME)
.then(
() => {
// request status is 200
this.setState({ isExist: true })
},
() => {
// request is failed
this.setState({ isExist: false })
}
);
}
render() {
if (this.state.isExist === true) {
return <img src={ MY_HOST + "/public/" + this.props.MY_IMAGE_NAME }/>
}
return <img src="/public/no-image.jpg"/>
}
}

Resources