getting error only with vercel deployment when displaying props (works locally) - reactjs

I am building a headless wordpress CMS(and using next.js template) .
I was able to successfully deploy to the vercel servers, I then started to add some content, in this case the Wordpress title field.. and this works great on my local server and display the title properly with no errors.. but when I update my git it kills the vercel deployment and I get this error.. I also get this error if I try to use content or dangerouslySetHTML
to clarify, if I remove this, it deploys fine
{ page.title }
Unhandled error during request: TypeError: Cannot read property 'title' of undefined
--
17:01:15.529 | at Page (/vercel/workpath0/.next/serverless/pages/[slug].js:1634:412)
this is my page code [slug].js
import Head from 'next/head'
import Link from 'next/link'
import Container from '../components/container'
import MoreStories from '../components/more-stories'
import HeroPost from '../components/hero-post'
import Intro from '../components/intro'
import Layout from '../components/layout'
import { getAllPagesWithSlug, getAllPagesBySlug } from '../lib/api'
import { CMS_NAME } from '../lib/constants'
import Header from '../components/header'
export default function Page( {page} ) {
return (
<>
<Layout>
<Head>
<title></title>
</Head>
<Header />
<Container>
{ page.title }
</Container>
</Layout>
</>
)
}
export async function getStaticProps({ params }) {
const data = await getAllPagesBySlug(params.slug)
console.log(data)
return {
props: {
page: data.page,
},
}
}
export async function getStaticPaths() {
const allPages = await getAllPagesWithSlug()
return {
//paths: [ { params: { slug: '${node.uri}' } } ],
paths: allPages.edges.map(({ node }) => `/${node.slug}`) || [],
fallback: true,
}
}
this is my query lib/api
const API_URL = process.env.WORDPRESS_API_URL
async function fetchAPI(query, { variables } = {}) {
const headers = { 'Content-Type': 'application/json' }
if (process.env.WORDPRESS_AUTH_REFRESH_TOKEN) {
headers[
'Authorization'
] = `Bearer ${process.env.WORDPRESS_AUTH_REFRESH_TOKEN}`
}
const res = await fetch(API_URL, {
method: 'POST',
headers,
body: JSON.stringify({
query,
variables,
}),
})
const json = await res.json()
if (json.errors) {
console.error(json.errors)
throw new Error('Failed to fetch API')
}
return json.data
}
export async function getAllPagesBySlug($id) {
const data = await fetchAPI(`
{
page(id: "${$id}", idType: URI) {
uri
slug
content
title
featuredImage {
node {
sourceUrl
}
}
}
}
`)
return data
}

Related

Google OAuth components must be used within GoogleOAuthProvider

I want to build my next js project in which i am using
https://www.npmjs.com/package/#react-oauth/google
but when I build it i get the following :
this is layout.js and in _app.js I have all the components wrapped in GoogleOAuthProvider
import { GoogleLogin } from '#react-oauth/google';
import {FcGoogle} from "react-icons/Fc"
import { useGoogleLogin } from '#react-oauth/google';
export default function Layout({ children }) {
const client_id = ""
const responseGoogle = (response) => {
console.log(response);
}
CUTTED (NOT RELEVANT)
const login = useGoogleLogin({
onSuccess: codeResponse => {
const { code } = codeResponse;
console.log(codeResponse)
axios.post("http://localhost:8080/api/create-tokens", { code }).then(response => {
const { res, tokens } = response.data;
const refresh_token = tokens["refresh_token"];
const db = getFirestore(app)
updateDoc(doc(db, 'links', handle), {
refresh_token : refresh_token
})
updateDoc(doc(db, 'users', useruid), {
refresh_token : refresh_token
}).then(
CUTTED (NOT RELEVANT)
)
}).catch(err => {
console.log(err.message);
})
},
onError: errorResponse => console.log(errorResponse),
flow: "auth-code",
scope: "https://www.googleapis.com/auth/calendar"
});
return (
<>
CUTTED (NOT RELEVANT)
</>
)
}
Everything works perfect in dev mode but it does not want to build
I've faced this issue too. So I use 'GoogleLogin' instead of 'useGoogleLogin', then you can custom POST method on 'onSuccess' property.
import { GoogleLogin, GoogleOAuthenProvider} from '#react-oauth/google';
return(
<GoogleOAuthProvider clientId="YOUR CLIENT ID">
<GoogleLogin
onSuccess={handleLogin}
/>
</GoogleOAuthProvider>
The async function will be like...
const handleLogin = async = (credentialResponse) => {
var obj = jwt_decode(credentialResponse.credential);
var data = JSON.stringify(obj);
console.log(data);
const data = {your data to send to server};
const config = {
method: 'POST',
url: 'your backend server or endpoint',
headers: {},
data: data
}
await axios(config)
}
Spending whole day, this solve me out. Just want to share.
You have to wrap your application within GoogleOAuthProvider component. Please keep in mind that you will need your client ID for this.
import { GoogleOAuthProvider } from '#react-oauth/google';
<GoogleOAuthProvider clientId="<your_client_id>">
<SomeComponent />
...
<GoogleLoginButton onClick={handleGoogleLogin}/>
</GoogleOAuthProvider>;

Error when using the next.js API with RecoilJS

I'm trying to initialise a Recoil atom using the Next API but encountering an error.
The default value is set to the function that makes the call to the Next API endpoint, which then retrieves some data from firebase.
When I then try to use the atom in a component using useRecoilState and log its value, I get this error:
error - TypeError [ERR_INVALID_URL]: Invalid URL
at new NodeError (node:internal/errors:371:5)
at onParseError (node:internal/url:552:9)
at new URL (node:internal/url:628:5)
at dispatchHttpRequest (file:///C:/Users/JoelMcMahon/projects/amt/amtAdmin/amt-admin-utility-v2/node_modules/axios/lib/adapters/http.js:169:20)
at new Promise (<anonymous>)
at httpAdapter (file:///C:/Users/JoelMcMahon/projects/amt/amtAdmin/amt-admin-utility-v2/node_modules/axios/lib/adapters/http.js:105:10)
at Axios.dispatchRequest (file:///C:/Users/JoelMcMahon/projects/amt/amtAdmin/amt-admin-utility-v2/node_modules/axios/lib/core/dispatchRequest.js:46:10)
at Axios.request (file:///C:/Users/JoelMcMahon/projects/amt/amtAdmin/amt-admin-utility-v2/node_modules/axios/lib/core/Axios.js:140:33)
at wrap (file:///C:/Users/JoelMcMahon/projects/amt/amtAdmin/amt-admin-utility-v2/node_modules/axios/lib/helpers/bind.js:5:15)
at eval (webpack-internal:///./src/Modules/getUsers.ts:12:58) {
input: '/api/users/getUsersFromDatabase',
code: 'ERR_INVALID_URL',
page: '/'
}
I've also tried setting the default value of the atom as a selector that makes the query using async await but still get the error.
Here are the relevant files:
atoms.js:
import { atom } from "recoil";
import { getUsers } from "../Modules/getUsers";
export const userListPromise = atom({
key: "userListPromise",
default: getUsers(),
});
getUsers.ts:
import axios from "axios";
export const getUsers = (): Promise<any> => {
return new Promise((resolve, reject) => {
axios({
method: "GET",
url: "/api/users/getUsersFromDatabase",
})
.then((response) => {
resolve(response.data);
})
.catch((error) => {
reject(error);
});
});
};
getUsersFromDatabase.ts
import axios from "axios";
import type { NextApiRequest, NextApiResponse } from "next";
export default function handler(req: NextApiRequest, res: NextApiResponse) {
const url = //My Cloud Function URL//;
axios({
method: "GET",
url: url,
})
.then((response) => {
res.status(200).json(response.data);
})
.catch((error) => {
res.status(400).json({ message: `Failed to get users: ${error}` });
});
}
UserDisplay.tsx:
import React from "react";
import { useRecoilState } from "recoil";
import { userListPromise } from "../Atoms/atoms";
import { getUsers } from "../Modules/getUsers";
const UserDisplay = () => {
const [userList] = useRecoilState(userListPromise);
console.log(userList);
return (
<div>
</div>
);
};
export default UserDisplay;
If I comment out the lines using the state in UserDisplay.tsx:
const [userList] = useRecoilState(userListPromise);
console.log(userList);
then start the development server, uncomment them and save causing a live reload, then the error does not occur. However, if I then refresh the page or try to start the server initially with those lines uncommented, I get the error.
Any help or guidance would be greatly appreciated.
I'm using next v12.3.1 and recoil v0.7.6

Fetch the image and display it with Authorization in react

I'm going to fetch an image from ASP.NET core 5 web API and display it in react (with Authorization)
But I get the following error
Error image
when I remove Authorize and open the photo in the browser, the photo is displayed correctly
This is my code in react :
import axios from "axios";
import React, { useEffect, useState } from "react";
import { Buffer } from "buffer";
const Test = () => {
const [source, setSource] = useState();
useEffect(async () => {
const API_URL =
process.env.REACT_APP_URL +
"/Images/testimg/94e51231-cab8-4c51-8ee5-15b0da3164a4.jpg";
const token = JSON.parse(localStorage.getItem("user")).token;
try {
const response = await axios.get(API_URL, {
headers: {
responseType: "arraybuffer",
Authorization: `Bearer ${token}`,
},
});
if (response) {
console.log(response);
var buffer = Buffer.from(response.data,"base64")
setSource(buffer);
}
} catch (error) {
console.log(error);
}
}, []);
console.log(source);
return (
<img
id="test-img"
src={`data:image/jpeg;charset=utf-8;base64,${source}`}
/>
);
};
export default Test;
And This is my code in ASP.NET core 5 web API:
[Route("testimg/{name}")]
[HttpGet]
[Authorize]
public IActionResult testimg(string name)
{
string curentPath = Directory.GetCurrentDirectory();
string fullPath = Path.Combine(curentPath, $"resources\\{name}");
var image = System.IO.File.OpenRead(fullPath);
return File(image, "image/jpeg");
}

getting API resolved without sending a response for this may result in stalled requests error in nextjs

if I console.log the data in client side, it prints the data. But if I try to render the data, it doesn't render
And I getting the message API resolved without sending a response for /api/getdata, this may result in stalled requests.
api
export default async (req, res) => {
if (req.method === "GET") {
db.query(`SELECT * FROM todo`, (err, result) => {
res.status(200).json(JSON.stringify(result));
});
} else {
res.status(404).json({ message: "Can't post" });
}
};
clientside
import Head from "next/head";
import styles from "../styles/Home.module.css";
import Link from "next/link";
import { url } from "../config";
export const getServerSideProps = async () => {
const res = await fetch(`${url}/api/getdata`);
const data = await res.json();
return {
props: {
data,
},
};
};
export default function Home({ data }) {
console.log(data);
return (
<div className={styles.home}>
<Link href="/create">
<a className="btn">Create New Todo</a>
</Link>
{data.map((elem) => {
<h1>{elem.title}</h1>;
})}
</div>
);
}

nextjs sitemap error. type error: can not assign to read only property "undefined" of object "#<Object>"

hi everyone ! i am stuck with an error. ı implemented sitemap.xml.js
fıle in page folder. It is working in dev server but don't work in
production. using vercel hosting. Can you help?
import React from "react";
import axios from "axios";
import { API_URL } from "../lib/services"
const sitemapXML = data => {
let projectsXML = "";
let comUrlsXml = "";
data.map(post => {
const projectURL = https://example/${post.cSlug}/${post.pSlug};
projectsXML += `
<url>
<loc>${projectURL}</loc>
<priority>0.50</priority>
</url>`;
});
data.map(post => {
const comUrls = https://example/t/${post.cSlug};
comUrlsXml += `
<url>
<loc>${comUrls}</loc>
<priority>0.50</priority>
</url>`;
});
return `<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
${projectsXML}
${comUrlsXml}
</urlset>`;
};
class Sitemap extends React.Component {
}
export async function getServerSideProps({ res }) {
process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";
const data = await axios
.get(`${API_URL}/post/get-slugs`)
.then(response => response.data);
res.setHeader("Content-Type", "text/xml");
res.write(sitemapXML(data));
res.end();
return { props: { data } }
}
export default Sitemap;
i get error only prodcution

Resources