I'm trying to deploy a Next application with Prismic and i'm getting this error in the building process.
I have tried the solution with the webhook configuration in the Vercel servers without sucess Prismic Webhooks
Here is the [slug].tsx code:
export const getStaticPaths: GetStaticPaths = async () => {
return {
paths: [],
fallback: 'blocking'
}
}
export const getStaticProps: GetStaticProps = async ({ params }) => {
const prismic = getPrismicClient()
const { slug } = params;
const response = await prismic.getByUID('post', String(slug), {})
const post = {
slug,
title: RichText.asText(response.data.title),
content: RichText.asHtml(response.data.content),
updatedAt: new Date(response.last_publication_date).toLocaleDateString('pt-BR', {
day: '2-digit',
month: 'long',
year: 'numeric'
})
};
return {
props: {
post,
},
redirect: 60 * 60 * 24 * 7 //7 dias
}
}
This is the prismic.ts file:
import Prismic from '#prismicio/client'
export function getPrismicClient(req?: unknown) {
const prismic = Prismic.client(
process.env.PRISMIC_ENDPOINT,
{
req,
accessToken: process.env.PRISMIC_ACCESS_TOKEN
}
)
return prismic;
}
Here is the error log from Vercel:
22:13:41.009 Error occurred prerendering page "/posts". Read more: https://nextjs.org/docs/messages/prerender-error
22:13:41.009 TypeError: Only absolute URLs are supported
22:13:41.010 at getNodeRequestOptions (/vercel/path0/node_modules/node-fetch/lib/index.js:1305:9)
22:13:41.010 at /vercel/path0/node_modules/node-fetch/lib/index.js:1410:19
22:13:41.010 at new Promise (<anonymous>)
22:13:41.010 at fetch (/vercel/path0/node_modules/node-fetch/lib/index.js:1407:9)
22:13:41.011 at fetch (/vercel/path0/node_modules/cross-fetch/dist/node-ponyfill.js:10:20)
22:13:41.011 at fetchRequest (/vercel/path0/node_modules/#prismicio/client/cjs/#prismicio/client.js:989:24)
22:13:41.011 at DefaultRequestHandler.request (/vercel/path0/node_modules/#prismicio/client/cjs/#prismicio/client.js:1026:9)
22:13:41.011 at HttpClient.request (/vercel/path0/node_modules/#prismicio/client/cjs/#prismicio/client.js:1037:29)
22:13:41.011 at /vercel/path0/node_modules/#prismicio/client/cjs/#prismicio/client.js:1059:27
22:13:41.012 at DefaultApiCache.get (/vercel/path0/node_modules/#prismicio/client/cjs/#prismicio/client.js:956:19)
22:13:41.012 info - Generating static pages (3/7)
22:13:41.025 info - Generating static pages (5/7)
22:13:41.057 info - Generating static pages (7/7)
22:13:41.058 > Build error occurred
22:13:41.060 Error: Export encountered errors on following paths:
22:13:41.060 /posts
22:13:41.060 at /vercel/path0/node_modules/next/dist/export/index.js:31:1106
22:13:41.061 at runMicrotasks (<anonymous>)
22:13:41.061 at processTicksAndRejections (internal/process/task_queues.js:95:5)
22:13:41.062 at async Span.traceAsyncFn (/vercel/path0/node_modules/next/dist/telemetry/trace/trace.js:6:584)
22:13:41.062 at async /vercel/path0/node_modules/next/dist/build/index.js:43:49
22:13:41.062 at async Span.traceAsyncFn (/vercel/path0/node_modules/next/dist/telemetry/trace/trace.js:6:584)
22:13:41.062 at async /vercel/path0/node_modules/next/dist/build/index.js:25:1529
22:13:41.062 at async Span.traceAsyncFn (/vercel/path0/node_modules/next/dist/telemetry/trace/trace.js:6:584)
22:13:41.094 error Command failed with exit code 1.
22:13:41.094 info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
22:13:41.117 Error: Command "yarn run build" exited with 1
Related
This question already has answers here:
Fetch error when building Next.js static website in production
(1 answer)
NextJS/Vercel/MongoDB FetchError: request to http://localhost:3000/api/gear failed, reason: connect ECONNREFUSED 127.0.0.1:3000
(1 answer)
Closed 5 months ago.
In development, the project runs smoothly, but when I try to deploy on vercel I get the error
Error occurred prerendering page "/".
FetchError: request to http://localhost:3000/api/getPageInfo failed, reason: connect ECONNREFUSED 127.0.0.1:3000
if i try to access the 'http://localhost:3000/api/getPageInfo' from any browser i can do it, its available. there are 2 more env var, besides NEXT_PUBLIC_BASE_URL, NEXT_PUBLIC_SANITY_DATASET which is = 'production' and NEXT_PUBLIC_SANITY_PROJECT_ID to access the project in sanity studio. they are all configured in vercel
NEXT_PUBLIC_BASE_URL = http://localhost:3000
import type { NextApiRequest, NextApiResponse } from "next";
import { groq } from 'next-sanity';
import { sanityClient } from "../../sanity";
import { Experience } from "../../typings";
const query = groq`
*[_type == 'experience'] {
...,
technologies[]->
}
`;
type Data = {
experiences: Experience[];
}
export default async function handler(
req: NextApiRequest,
res: NextApiResponse<Data>
) {
const experiences: Experience[] = await sanityClient.fetch(query);
res.status(200).json({ experiences })
}
import { Experience } from '../../typings';
export const fetchExperiences = async() => {
const res = await fetch(`${process.env.NEXT_PUBLIC_BASE_URL}/api/getExperience`);
const data = await res.json()
const experiences: Experience[] = data.experiences;
return experiences;
}
// ON THE INDEX PAGE (the fetch of the 5 props follows the model above)
export const getStaticProps: GetStaticProps<Props> = async () => {
const pageInfo: PageInfo = await fetchPageInfo();
const experiences: Experience[] = await fetchExperiences();
const skills: Skill[] = await fetchSkills();
const projects: Project[] = await fetchProjects();
const socials: Social[] = await fetchSocials();
return {
props: {
pageInfo,
experiences,
skills,
projects,
socials,
},
revalidate: 10,
}
}
When I try to execute a slash command it crashes with an 404 error.
I already tried to delete all commands but it didn't work.
Here's the code I'm using
const commands = [
{
name: 'ping',
description: 'Replies with Pong!'
}];
const rest = new REST({ version: '9' }).setToken('token');
(async () => {
try {
console.log('Reloading slash commands');
await rest.put(
Routes.applicationGuildCommands("client_id", "server_id"),
{ body: commands },
);
console.log("Reloaded slash commands");
} catch (error) {
console.error(error);
}
})();
Here's the error
node_modules/discord.js/src/rest/RequestHandler.js:350
throw new DiscordAPIError(data, res.status, request);
^
DiscordAPIError: Unknown application command
at RequestHandler.execute (/home/container/node_modules/discord.js/src/rest/RequestHandler.js:350:13)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async RequestHandler.push (/home/container/node_modules/discord.js/src/rest/RequestHandler.js:51:14)
at async GuildApplicationCommandManager.fetch (/home/container/node_modules/discord.js/src/managers/ApplicationCommandManager.js:93:23)
at async Client.<anonymous> (/home/container/index.js:101:17) {
method: 'get',
path: '/applications/client_id/guilds/guild_id/commands/command_id',
code: 10063,
httpStatus: 404,
requestData: { json: undefined, files: [] }
}
if you want to register your Slash Commands with the moderately recent Discord.js Rest library you have to use the builder library as well. You are also not passing JSON to the body you are passing an Array of Objects.
From Discord.js Guide on Making Slash Commands
const { SlashCommandBuilder } = require('#discordjs/builders');
const { REST } = require('#discordjs/rest');
const { Routes } = require('discord-api-types/v9');
const commands = [
new SlashCommandBuilder().setName('ping').setDescription('Replies with pong!'),
new SlashCommandBuilder().setName('server').setDescription('Replies with server info!'),
new SlashCommandBuilder().setName('user').setDescription('Replies with user info!'),
]
.map(command => command.toJSON());
const rest = new REST({ version: '9' }).setToken(token);
rest.put(Routes.applicationGuildCommands(clientId, guildId), { body: commands })
.then(() => console.log('Successfully registered application commands.'))
.catch(console.error);
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!
I don't understand these errors when I export as production npm run build , but when I test npm run dev it works just fine. I use getStaticProps and getStaticPath fetch from an API route.
First when I npm run build
FetchError: invalid json response body at https://main-website-next.vercel.app/api/products reason: Unexpected token T in JSON at position
0
at D:\zummon\Main Website\main-website-next\node_modules\node-fetch\lib\index.js:272:32
at processTicksAndRejections (internal/process/task_queues.js:97:5)
at async getStaticPaths (D:\zummon\Main Website\main-website-next\.next\server\pages\product\[slug].js:1324:18)
at async buildStaticPaths (D:\zummon\Main Website\main-website-next\node_modules\next\dist\build\utils.js:16:80)
at async D:\zummon\Main Website\main-website-next\node_modules\next\dist\build\utils.js:26:612
at async D:\zummon\Main Website\main-website-next\node_modules\next\dist\build\tracer.js:1:1441 {
type: 'invalid-json'
}
\pages\product\[slug]
import { assetPrefix } from '../../next.config'
export default function Page(){...}
export const getStaticProps = async ({ params: { slug }, locale }) => {
const res = await fetch(`${assetPrefix}/api/products/${slug}`)
const result = await res.json()
const data = result.filter(item => item.locale === locale)[0]
const { title, keywords, description } = data
return {
props: {
data,
description,
keywords,
title
}
}
}
export const getStaticPaths = async () => {
const res = await fetch(`${assetPrefix}/api/products`)
const result = await res.json()
const paths = result.map(({ slug, locale }) => ({ params: { slug: slug }, locale }))
return {
fallback: true,
paths,
}
}
next.config.js
const isProd = process.env.NODE_ENV === 'production'
module.exports = {
assetPrefix: isProd ? 'https://main-website-next.vercel.app' : 'http://localhost:3000',
i18n: {
localeDetection: false,
locales: ['en', 'th'],
defaultLocale: 'en',
}
}
API routes
// pages/api/products/index.js
import data from '../../../data/products'
export default (req, res) => {
res.status(200).json(data)
}
// pages/api/products/[slug].js
import db from '../../../data/products'
export default ({ query: { slug } }, res) => {
const data = db.filter(item => item.slug === slug)
if (data.length > 0) {
res.status(200).json(data)
} else {
res.status(404).json({ message: `${slug} not found` })
}
}
// ../../../data/products (data source)
module.exports = [
{ locale: "en", slug: "google-sheets-combine-your-cashflow",
title: "Combine your cashflow",
keywords: ["Google Sheets","accounting"],
description: "...",
},
...
]
Second when I remove the production domain, I run npm run build but still get the error like
TypeError: Only absolute URLs are supported
at getNodeRequestOptions (D:\zummon\Main Website\main-website-next\node_modules\node-fetch\lib\index.js:1305:9)
at D:\zummon\Main Website\main-website-next\node_modules\node-fetch\lib\index.js:1410:19
at new Promise (<anonymous>)
at fetch (D:\zummon\Main Website\main-website-next\node_modules\node-fetch\lib\index.js:1407:9)
at getStaticPaths (D:\zummon\Main Website\main-website-next\.next\server\pages\[slug].js:938:21)
at buildStaticPaths (D:\zummon\Main Website\main-website-next\node_modules\next\dist\build\utils.js:16:86)
at D:\zummon\Main Website\main-website-next\node_modules\next\dist\build\utils.js:26:618
at processTicksAndRejections (internal/process/task_queues.js:97:5)
at async D:\zummon\Main Website\main-website-next\node_modules\next\dist\build\tracer.js:1:1441 {
type: 'TypeError'
}
My next.config.js after remove
const isProd = process.env.NODE_ENV === 'production'
module.exports = { //remove
assetPrefix: isProd ? '' : 'http://localhost:3000',
i18n: {
localeDetection: false,
locales: ['en', 'th'],
defaultLocale: 'en',
}
}
My package.json when I npm run build script
{
"name": "main-website-next",
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build && next export",
"start": "next start"
},
"dependencies": {
"next": "10.0.6",
"react": "17.0.1",
"react-dom": "17.0.1"
}
}
You should not call an internal API route inside getStaticProps. Instead, you can safely use your API logic directly in getStaticProps/getStaticPaths. These only happen server-side so you can write server-side code directly.
As getStaticProps runs only 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, so you can write direct database queries without them being
sent to browsers.
This means that instead of fetching an API route from
getStaticProps (that itself fetches data from an external source),
you can write the server-side code directly in getStaticProps.
Furthermore, your API routes are not available during build-time, as the server has not been started at that point.
Here's a small refactor of your code to address the issue.
// /pages/product/[slug]
import db from '../../../data/products'
// Remaining code..
export const getStaticProps = async ({ params: { slug }, locale }) => {
const result = db.filter(item => item.slug === slug)
const data = result.filter(item => item.locale === locale)[0]
const { title, keywords, description } = data
return {
props: {
data,
description,
keywords,
title
}
}
}
export const getStaticPaths = async () => {
const paths = db.map(({ slug, locale }) => ({ params: { slug: slug }, locale }))
return {
fallback: true,
paths,
}
}
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