Project deployment with next js - reactjs

I have a question about a project deployment with NextJS/Vercel.
According to documentation, await fetch is supporting only absolute URLs. Example:
export async function getStaticProps(context) {
const route = process.env.APIpath + 'api/category/getCategories';
const res = await fetch(route)
const json = await res.json()
return {
props: {
data: json,
},
};
}
where APIpath: 'http://localhost:3000/',
Question: How can I deploy a project on vercel.com/test/my_project? because when I only change process.env.APIpath to vercel.com/test/my_project = error.
P.S. Error message
Build error occurred
Error: Export encountered errors on following paths:
categories/database/categoryList - the page I am calling getStaticProps(context) above

Related

NextJs 13(app dir) fetch data from build in api

I am using Nextjs 13 with /src and /app directory. Below I am trying to fetch data from nextjs api:
//src/app/page.tsx
const getProducts = async () => {
try {
const res = await fetch('/api/products');
const data = await res.json();
return data;
} catch (err) {
console.log(err);
}
}
export default async function Home() {
....
}
//src/pages/api/products
export default function handler(
req: NextApiRequest,
res: NextApiResponse<Product[]>
) {
res.status(200).json(products)
}
this doesn't work and instead show Failed to parse URL from /api/products and TypeError [ERR_INVALID_URL]: Invalid URL.
Note: When I fetch the same data using localhost:3000 with url that does work perfectly fine.
I even tried using `/pages/api/products' that doesn't work either.
please create index.js inside /api/products/index.js and then build your endpoint and call that from Component as you did above
e.g
export default function handler(req, res) {
res.status(200).json([{id:1, title:'T-Shirt'},{id:2,title:'Shoes'}]);
}

In Next.js when fetching data from ghost CMS it ends up in 502 error only on first load

I'm using Heroku free plan to host the blog section of a website in Ghost CMS and use Next.js for the front(netlify) to fetch the data from it. On first loading I'm getting an 502 error - Runtime.UnhandledPromiseRejection - FetchError: invalid json response body / Unexpected token < in JSON at position 0. By refreshing the page everything works as expected. Then when the dyno sleeps and someone click the blog url again and wakes the dyno, the same behaviour occurs.
async function getPosts() {
const res = await fetch(
`${BLOG_URL}/ghost/api/v4/content/posts/?key=${CONTENT_API_KEY}&fields=title,slug,custom_excerpt,published_at`,
);
const data = await res.json();
if (!data) {
return {
redirect: {
destination: '/',
permanent: false,
},
};
}
const posts = data.posts;
return posts;
}
export const getStaticProps = async ({ params }) => {
const posts = await getPosts();
return {
props: { posts },
revalidate: 3,
};
};
This is the code for the blog page and similar for the slug page. It seems that JSON is invalid during the call and "if (!data)" does not handling the error. Any ideas why this error appears and if there is a solution?

Error during deplyment in Next.js app // getStaticPaths is failing

I am having an issue when trying to deploy my app using Vercel. I am using dynamic routes for my projects pages, therefore I am using getStaticPaths and getStaticProps in the page. The code should call an API that retrieve my records from Airtable, however, it was failing as we should not call the APIs in there, so I have replaced the API call for the API code, it is working for me in localhost, even when I use npm run build. However, when I push my code to GH, Vercel cannot build it with the following error:
message: 'there was an error retrieving the records for paths',
e: AirtableError {
error: 'NOT_FOUND',
message: 'Could not find what you are looking for',
statusCode: 404
}
}
Build error occurred
TypeError: Cannot read property 'map' of undefined
at getStaticPaths (/vercel/path0/.next/server/pages/projects/[project].js:97:29)
at processTicksAndRejections (internal/process/task_queues.js:95:5)
at async buildStaticPaths (/vercel/path0/node_modules/next/dist/build/utils.js:498:31)
at async /vercel/path0/node_modules/next/dist/build/utils.js:641:119
at async Span.traceAsyncFn (/vercel/path0/node_modules/next/dist/trace/trace.js:75:20) {
type: 'TypeError'
}
Error: Command "npm run build" exited with 1
import Image from "next/image";
import Link from "next/link";
import { projectsTable } from "../../airtable/airtable";
export const getStaticPaths = async () => {
const fetchProjects = async () => {
try {
let projects = [];
await projectsTable.select().eachPage((records, fetchNextPage) => {
records.forEach((record) => {
projects.push(record.fields);
});
fetchNextPage();
});
return projects;
} catch (e) {
return console.log({
message: "there was an error retrieving the records for paths",
e,
});
}
};
const projects = await fetchProjects();
const paths = projects.map((project) => {
return {
params: { project: project.name.toLowerCase().toString() },
};
});
return {
paths,
fallback: false,
};
};
export const getStaticProps = async (context) => {
const fetchProjects = async () => {
try {
let projects = [];
await projectsTable.select().eachPage((records, fetchNextPage) => {
records.forEach((record) => {
projects.push(record.fields);
});
fetchNextPage();
});
return projects;
} catch (e) {
return console.log({
message: "there was an error retrieving the records for props",
e,
});
}
};
const projectName = context.params.project;
const projects = await fetchProjects();
const project = projects.find(
(project) => project.name.toLowerCase().toString() == projectName
);
return {
props: { project },
};
};
The code is just fetching the array of projects and use the name to find the correct one and use it as props to generate the rest of the page content. I tried to debug it using console.log, but the projects array is correct when I try, and I dont get any other error T.T Could anyone help me with this? Anyone having same issue or maybe could spot the error in my code? Thank you a lot in advance!

NextJS: error in getServerSideProps function with axios

On the main page (index.js file) I use the getServerSideProps function
export async function getServerSideProps(context) {
axios.defaults.headers.common['Lang'] = context.locale
try {
const response = await axios.get('/index?limit=8')
return {
props: {
data: response.data
},
};
} catch (error) {
return {
props: {
error: error
},
};
}
}
Everything used to work, but now it's starting to make a mistake
connect EADDRNOTAVAIL ip:443 - Local (ip:0)
Although if you make a request to the same address in useEffect () - everything works
Tried to upgrade next to version 12 - the error remained
Screenshot
try
const response = await axios.get(`https://yourserver.com/index?limit=8`)
and if works replace https://yourserver.com by your .env variable
Also, try to console.log your variable:
const response = await axios.get('/index?limit=8')
console.log(response)
And check if your API route has .get method
In getServerSideProps you have to type the whole url http://localhost:3000/api/my-end-point
So I have two instances of axios in nextjs.
import Axios from 'axios'
// Use in react component
const ClientAxios = Axios.create({
baseURL: '/api'
})
// Use in getServerSideProps
const SystemAxios = Axios.create({
baseURL: 'http://localhost:3000/api'
})

ReactJS Failed to construct 'WebSocket': The subprotocol '[object Object]' is invalid

I'm getting the following error in my react application using enigma.js (https://qlik.dev/apis/javascript/enigmajs) . I'm trying to initialize a WebSocket connection and im getting the error. "Failed to construct 'WebSocket': The subprotocol '[object Object]' is invalid".
The WebSocket connection URL is correct as it can be tested with https://catwalk.core.qlik.com/?engine_url=wss://sense-demo.qlik.com/app/133dab5d-8f56-4d40-b3e0-a6b401391bde which returns the data. You can try by editing the URL which will return an error.
the code is
async init() {
const appId = "133dab5d-8f56-4d40-b3e0-a6b401391bde";
const url =
"wss://sense-demo.qlik.com/app/133dab5d-8f56-4d40-b3e0-a6b401391bde";
const session = enigma.create({
schema,
createSocket: () =>
new WebSocket(url, {
}),
});
const global = await session.open();
const app = await global.openDoc(appId);
const appLayout = await app.getAppLayout();
console.log(appLayout);
}
I found the solution:
qDoc.config.js
const enigma = require('enigma.js');
const schema = require('enigma.js/schemas/12.20.0.json');
const SenseUtilities = require('enigma.js/sense-utilities');
const config = {
host: 'sense-demo.qlik.com',
secure: true,
port: 443,
prefix: '',
appId: '133dab5d-8f56-4d40-b3e0-a6b401391bde',
};
const url = SenseUtilities.buildUrl(config);
async function init() {
const session = enigma.create({
schema,
url,
suspendOnClose: true,
});
const global = await session.open();
const app = await global.openDoc(config.appId);
const appLayout = await app.getAppLayout();
console.log(appLayout);
}
init();
const session = enigma.create({ schema, url, suspendOnClose: true });
// open doc and return promise which will resolve to doc
export const openDoc = () => (
session.open().then((global) => global.openDoc(config.appId))
);
// close session
export const closeSession = () => (
session.close()
);
INSTURCTION
downoad this project
delete package-lock.json file
npm i
npm run-script dev
This is the direvtory view:
This is result log:
The solution is explained here
https://github.com/qlik-oss/enigma.js/issues/889

Resources