This question already has an answer here:
Fetch error when building Next.js static website in production
(1 answer)
Closed 12 months ago.
The app fetches data from local Javascript file via an api. Here is below the error and code.
$ npm run build
next-crash-course#0.1.0 build
next build && next export
Browserslist: caniuse-lite is outdated. Please run:
npx browserslist#latest --update-db
info - Creating an optimized production build
info - Compiled successfully
Build error occurred
FetchError: request to http://localhost:3000/api/articles failed, reason: connect ECONNREFUSED 127.0.0.1:3000
at ClientRequest. (C:\WebTest_NextJS(Brad Traversy)\pr1\node_modules\node-fetch\lib\index.js:1461:11)
at ClientRequest.emit (node:events:369:20)
at Socket.socketErrorListener (node:_http_client:462:9)
at Socket.emit (node:events:369:20)
at emitErrorNT (node:internal/streams/destroy:188:8)
at emitErrorCloseNT (node:internal/streams/destroy:153:3)
at processTicksAndRejections (node:internal/process/task_queues:81:21) {
type: 'system',
errno: 'ECONNREFUSED',
code: 'ECONNREFUSED'
}
info - Collecting page data .npm ERR! code 1
npm ERR! path C:\Test_NextJS\pr1
npm ERR! command failed
npm ERR! command C:\WINDOWS\system32\cmd.exe /d /s /c next build && next export
npm ERR! A complete log of this run can be found in:
npm ERR! C:\Users\MH1\AppData\Local\npm-cache_logs\2021-05-21T02_51_47_465Z-debug.log
NOTE: in the dev mode everything work fine.
Code link: https://github.com/bradtraversy/next-crash-course
When we are building with "next export" it will try to invoke the call to fetch the data Pages/index.js line 13. In Config/index.js it is expecting the API server is hosted somewhere "https://yourwebsite.com". As a workaround,
Modify "https://yourwebsite.com" to "http://localhost:3000" inside Config/index.js
Open one terminal and start "npm run dev"
Open 2nd terminal and execute "npm run build". As the API is running in localhost:3000, it will build properly.
Config/index.js
const dev = process.env.NODE_ENV !== 'production'
export const server = dev ? 'http://localhost:3000' : 'https://yourwebsite.com'
Pages/index.js
export const getStaticProps = async () => {
const res = await fetch(`${server}/api/articles`)
const articles = await res.json()
return {
props: {
articles,
},
}
}
URL: https://nextjs.org/docs/advanced-features/static-html-export
Browse the link in any browser. Example: http://localhost:3000/about
Related
I made a simple multipage app with vue 3.2 and vite 2.6
|-src
|---main.js
|-package.json
|-vite.config.js
|-index.html
|-validation_password.html
But when I want to build it: vite build only the index page (and not the validation-password).
I tried to modify my vite.config.js with rollup Options like here :
const { resolve } = require('path')
module.exports = defineConfig({
build: {
rollupOptions: {
input: {
main: resolve(__dirname, 'index.html'),
valpass: resolve(__dirname, 'validation_password.html')
}
}
}
})
the build failed. and i have this error in my terminal:
[rollup-plugin-dynamic-import-variables] Unexpected token (1:0)
file: C:/wamp64/www/IMB/VueJS/vuejs/src/PassVal.vue:1:0
error during build:
SyntaxError: Unexpected token (1:0)
at Parser.pp$5.raise (C:\wamp64\www\IMB\VueJS\vuejs\node_modules\rollup\dist\shared\rollup.js:19495:13)
at Parser.pp.unexpected (C:\wamp64\www\IMB\VueJS\vuejs\node_modules\rollup\dist\shared\rollup.js:16820:8)
at Parser.pp$4.parseExprAtom (C:\wamp64\www\IMB\VueJS\vuejs\node_modules\rollup\dist\shared\rollup.js:18870:10)
at Parser.pp$4.parseExprSubscripts (C:\wamp64\www\IMB\VueJS\vuejs\node_modules\rollup\dist\shared\rollup.js:18662:19)
at Parser.pp$4.parseMaybeUnary (C:\wamp64\www\IMB\VueJS\vuejs\node_modules\rollup\dist\shared\rollup.js:18628:17)
at Parser.pp$4.parseExprOps (C:\wamp64\www\IMB\VueJS\vuejs\node_modules\rollup\dist\shared\rollup.js:18561:19)
at Parser.pp$4.parseMaybeConditional (C:\wamp64\www\IMB\VueJS\vuejs\node_modules\rollup\dist\shared\rollup.js:18544:19)
at Parser.pp$4.parseMaybeAssign (C:\wamp64\www\IMB\VueJS\vuejs\node_modules\rollup\dist\shared\rollup.js:18512:19)
at Parser.pp$4.parseExpression (C:\wamp64\www\IMB\VueJS\vuejs\node_modules\rollup\dist\shared\rollup.js:18476:19)
at Parser.pp$1.parseStatement (C:\wamp64\www\IMB\VueJS\vuejs\node_modules\rollup\dist\shared\rollup.js:17010:45)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! components-portail-math#0.0.1 build: `vite build`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the components-portail-math#0.0.1 build script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
npm ERR! A complete log of this run can be found in:
npm ERR! C:\Users\willb\AppData\Roaming\npm-cache\_logs\2021-10-07T14_34_53_913Z-debug.log
My PassVal.vue file break no worries locally.
I don't understand. I'm following the doc.
I used Vue Router(I didn't know) to solve my problem.
I am trying to deploy an app to Vercel, and getting this error at build
14:13:58.168 Cloning github.com/ChrisB007/moodflics (Branch: main, Commit: 7a2acfe)
14:13:58.575 Cloning completed: 406.06ms
14:13:58.624 Analyzing source code...
14:13:59.946 Installing build runtime...
14:14:03.139 Build runtime installed: 3.193s
14:14:07.055 Build cache not provided
14:14:08.517 Installing dependencies...
14:14:09.142 npm WARN read-shrinkwrap This version of npm is compatible with lockfileVersion#1, but package-lock.json was generated for lockfileVersion#2. I'll try to do my best with it!
14:14:23.664 npm WARN moodflics#0.1.0 No repository field.
14:14:23.676 npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents#2.3.2 (node_modules/fsevents):
14:14:23.677 npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents#2.3.2: wanted {"os":"darwin","arch":"any"} (current: {"os":"linux","arch":"x64"})
14:14:23.681 added 387 packages from 281 contributors in 14.582s
14:14:23.836 62 packages are looking for funding
14:14:23.836 run `npm fund` for details
14:14:23.861 Detected Next.js version: 10.2.0
14:14:23.864 Running "npm run build"
14:14:24.144 > moodflics#0.1.0 build /vercel/path0
14:14:24.144 > next build
14:14:24.557 warn - React 17.0.1 or newer will be required to leverage all of the upcoming features in Next.js 11. Read more: https://nextjs.org/docs/messages/react-version
14:14:24.912 info - Using webpack 5. Reason: no custom webpack configuration in next.config.js https://nextjs.org/docs/messages/webpack5
14:14:25.052 info - Checking validity of types...
14:14:25.068 Attention: Next.js now collects completely anonymous telemetry regarding usage.
14:14:25.068 This information is used to shape Next.js' roadmap and prioritize features.
14:14:25.068 You can learn more, including how to opt-out if you'd not like to participate in this anonymous program, by visiting the following URL:
14:14:25.068 https://nextjs.org/telemetry
14:14:25.123 info - Creating an optimized production build...
14:14:29.905 Failed to compile.
14:14:29.906 ModuleNotFoundError: Module not found: Error: Can't resolve 'next-auth/client' in '/vercel/path0/pages'
14:14:29.906 > Build error occurred
14:14:29.907 Error: > Build failed because of webpack errors
14:14:29.907 at /vercel/path0/node_modules/next/dist/build/index.js:17:924
14:14:29.907 at async Span.traceAsyncFn (/vercel/path0/node_modules/next/dist/telemetry/trace/trace.js:6:584)
14:14:29.946 npm ERR! code ELIFECYCLE
14:14:29.947 npm ERR! errno 1
14:14:29.951 npm ERR! moodflics#0.1.0 build: `next build`
14:14:29.951 npm ERR! Exit status 1
14:14:29.951 npm ERR!
14:14:29.951 npm ERR! Failed at the moodflics#0.1.0 build script.
14:14:29.951 npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
14:14:29.959 npm ERR! A complete log of this run can be found in:
14:14:29.959 npm ERR! /vercel/.npm/_logs/2021-05-10T18_14_29_952Z-debug.log
14:14:29.972 Error: Command "npm run build" exited with 1
Everything seems to be working fine locally, but when I tried deploying it to Vercel I got the above error message. Can you tell me how to fix it?
Sometimes Vercel acts wired that my codes run locally(npm run dev) but fail after upload. This happens when I use Github automatic deployment, i.e. I directly push to my Github repo then Vercel automatically build and update.
However, using Vercel CLI solved my problem. run vercel for preview then vercel --prod for deployment in production
It can't resolve next-auth/client
ModuleNotFoundError: Module not found: Error: Can't resolve 'next-auth/client' in '/vercel/path0/pages'
Ensure that next-auth is properly installed as a dependency and not a dev dependency. Also upgrade your version of react, it's throwing a warning about it not being 17.01 or higher. If you are using typescript, try module augmentation via the next-auth namespace as indicated in their documentation for typescript namespaces. For example, an #/types/next.d.ts file and an #/types/next-auth.d.ts file for module augmentation.
Locally, I use nextauth as well, and have the following in my #/types/next.d.ts file:
import type { NextComponentType, NextPageContext } from 'next';
import type { Session } from 'next-auth';
import type { Router } from 'next/router';
declare module 'next/app' {
type AppProps<P = Record<string, unknown>> = {
Component: NextComponentType<NextPageContext, any, P>;
router: Router;
__N_SSG?: boolean;
__N_SSP?: boolean;
pageProps: P & {
/** Initial session passed in from getServerSideProps or getInitialProps */
session?: Session;
};
};
}
As for the contents of my #/types/next-auth.d.ts file, it's for a custom headless wordpress auth flow, but you can customize the Session/User interfaces regardless of whether you're using a custom approach or not
import NextAuth, { User } from 'next-auth';
import { JWT } from 'next-auth/jwt';
import { WordpressUserPartialFragment } from '../graphql/generated/graphql';
declare module 'next-auth' {
interface Session extends WordpressUserPartialFragment {
response: {
accessToken: string;
id: string;
avatar: {
url: string;
};
description: string | null;
slug: string;
username: string;
email: string;
firstName: string;
lastName: string;
token_exp: string;
refresh_token: string;
locale: string;
};
}
}
Delete node_modules and run yarn install.
Then do yarn build.
If you use npm then do npm i and npm run build instead of yarn install and yarn build.
Then deploy
Check .vercelignore file for folders/files you are missing.
In my case, I have included folder and forgot.
Also double check what source files got synced to vercel, under project deployments, source tab.
I'm trying to setup a Firebase project on Codeship CI/CD and I cannot seem to get the service credentials JSON key to work with my project when it's stored in an environment variable.
MVCE
Dev environment startup script
export FIREBASE_CREDENTIAL=BASE64ENCODED_credentials_json
export DATABASE_URL=https://my-project.firebaseio.com
echo $FIREBASE_CREDENTIAL | base64 -D > FIREBASE_CREDENTIAL.json
npm start
index.ts
import * as admin from "firebase-admin";
const credentials = require("../FIREBASE_CREDENTIAL.json");
const databaseURL = process.env.DATABASE_URL;
console.log(credentials.project_id); // succeeds
console.log(databaseURL); // is correct
admin.initializeApp({
...credentials,
databaseURL,
databaseAuthVariableOverride: { uid: "scraper" }
});
admin
.database()
.ref("/test")
.set(admin.database.ServerValue.TIMESTAMP);
Codeship script
echo $FIREBASE_CREDENTIAL | base64 -di > FIREBASE_CREDENTIAL.json
nvm install 8
npm install
npm test
Results
On dev machine, the write succeeds as expected
On Codeship CI container, I get this error.
console.warn node_modules/#firebase/logger/dist/index.cjs.js:66
[2018-10-05T12:53:51.316Z] #firebase/database: FIREBASE WARNING: {"code":"app/invalid-credential","message":"Credential implementation provided to initializeApp() via the \"credential\" property failed to fetch a valid Google OAuth2 access token with the following error: \"Failed to parse access token response: Error: Error while making request: getaddrinfo ENOTFOUND metadata.google.internal metadata.google.internal:80. Error code: ENOTFOUND\"."}
Background
Within an Electron app, sqlite3 doesn't work right after npm install --save. I got it working after doing some web research, by:
(1) downgrading my node version (via n) to match Electron's node version; and
(2) rebuilding sqlite with the right module name/targets with this package.json script:
"rebuild-sqlite3": "cd node_modules/sqlite3 && npm run prepublish && node-gyp configure --module_name=node_sqlite3 --module_path=../lib/binding/electron-v1.2-darwin-x64 && node-gyp rebuild --target=1.2.6 --arch=x64 --target_platform=darwin --dist-url=https://atom.io/download/atom-shell --module_name=node_sqlite3 --module_path=../lib/binding/electron-v1.2-darwin-x64"
After that, Sqlite3 works in development (i.e. when I run electron . in the project dir).
Problem
I package the app with electron-packager: "./node_modules/.bin/webpack -p && ./node_modules/electron-packager/cli.js ./ --out ./bin --platform=darwin --arch=x64 --version=1.2.6 --overwrite --ignore=\"ignore|bin|node_modules\""
When I open the app by double-clicking the created (appName).app, the console complains: `Uncaught Error: Cannot find module
Question
How can I get sqlite3 to be found in the final packaged product? Even "hacks" or workarounds are welcome, as I tried various fixes to no avail.
I leave this answer for someone who has the same problem and is wasting their time to figure out.
step1
npm install sqlite3
electron .
I expected to work fine. but I had an error 'cannot find node module sqlite3'
step2
npm install electron-rebuild --save-dev
electron-rebuild -f -w sqlite3
electron .
it worked.
but if you used 'electron-packager' to package and make executable file, It didn't work. the same error occured.
"electron-packager . electron-tutorial-app --overwrite --asar --platform=win32 --arch=ia32 --icon=assets/icons/win/icon.ico --prune=true --out=new --version-string.CompanyName=CE --version-string.FileDescription=CE --version-string.ProductName=\"Electron Test\"",
step3
I spent pretty much time to figure out. At the end, I figured out. the solution was using electron-packager API and integrating afterCopy with electron-rebuild.
# build.js
const packager = require('electron-packager');
const rebuild = require('electron-rebuild');
packager({
dir: '../dir',
overwrite: true,
asar: true,
platform: 'win32',
arch: 'ia32',
icon: 'assets/icons/win/icon.ico',
prune: true,
out: 'hello',
executableName: 'hello',
afterCopy: [(buildPath, electronVersion, platform, arch, callback) => {
rebuild.rebuild({ buildPath, electronVersion, arch })
.then(() => callback())
.catch((error) => callback(error));
}],
})
node build.js
reference
electron-rebuild manual 'How can I integrate this into Electron packager?'
electron-packager API doc
Doesn't the --ignore=\"ignore|bin|node_modules\" you pass to electron-packager ignore everything in the node_modules dir, the very place where the sqlite3 module is installed?
I am using mupx to deploy a meteor app to digital ocean. (Using a $5 droplet with 512 MB RAM).
After I deploy, mupx returns this error message:
> mupx deploy
Meteor Up: Production Quality Meteor Deployments
------------------------------------------------
Configuration file : mup.json
Settings file : settings.json
Meteor app path : /Users/me/myapp
Using buildOptions : {}
Started TaskList: Deploy app 'My-App' (linux)
[48.59.198.247] - Uploading bundle
[48.59.198.247] - Uploading bundle: SUCCESS
[48.59.198.247] - Sending environment variables
[48.59.198.247] - Sending environment variables: SUCCESS
[48.59.198.247] - Initializing start script
[48.59.198.247] - Initializing start script: SUCCESS
[48.59.198.247] - Invoking deployment process
[48.59.198.247] - Invoking deployment process: SUCCESS
[48.59.198.247] - Verifying deployment
[48.59.198.247] x Verifying deployment: FAILED
-----------------------------------STDERR-----------------------------------
0 0 0 0 0 0 0 0 --:--:-- --:--:-- --:--:-- 0
curl: (52) Empty reply from server
npm WARN package.json meteor-dev-bundle#0.0.0 No description
npm WARN package.json meteor-dev-bundle#0.0.0 No repository field.
npm WARN package.json meteor-dev-bundle#0.0.0 No README data
> fibers#1.0.5 install /bundle/bundle/programs/server/node_modules/fibers
> node ./build.js
`linux-x64-v8-3.14` exists; testing
Binary is fine; exiting
underscore#1.5.2 node_modules/underscore
semver#4.1.0 node_modules/semver
eachline#2.3.3 node_modules/eachline
└── type-of#2.0.1
chalk#0.5.1 node_modules/chalk
├── ansi-styles#1.1.0
├── escape-string-regexp#1.0.3
├── supports-color#0.2.0
├── has-ansi#0.1.0 (ansi-regex#0.2.1)
└── strip-ansi#0.3.0 (ansi-regex#0.2.1)
source-map-support#0.2.8 node_modules/source-map-support
└── source-map#0.1.32 (amdefine#0.1.0)
fibers#1.0.5 node_modules/fibers
=> Starting meteor app on port:80
=> Redeploying previous version of the app
------------------------------STDOUT-----------------------------
To see more logs type 'mup logs --tail=50'
-----------------------------------------------------------------
If I check the logs on the server (using mupx logs -f) I see the following:
[48.59.198.247] /opt/meteord/run_app.sh: line 36: 16 Killed node main.js
[48.59.198.247] npm WARN package.json meteor-dev-bundle#0.0.0 No description
[48.59.198.247] npm WARN package.json meteor-dev-bundle#0.0.0 No repository field.
[48.59.198.247] npm WARN package.json meteor-dev-bundle#0.0.0 No README data
[48.59.198.247] /opt/meteord/run_app.sh: line 36: 16 Killed node main.js
[48.59.198.247] npm WARN package.json meteor-dev-bundle#0.0.0 No description
[48.59.198.247] npm WARN package.json meteor-dev-bundle#0.0.0 No repository field.
[48.59.198.247] npm WARN package.json meteor-dev-bundle#0.0.0 No README data
[48.59.198.247] /opt/meteord/run_app.sh: line 36: 16 Killed node main.js
[48.59.198.247] npm WARN package.json meteor-dev-bundle#0.0.0 No description
[48.59.198.247] npm WARN package.json meteor-dev-bundle#0.0.0 No repository field.
[48.59.198.247] npm WARN package.json meteor-dev-bundle#0.0.0 No README data
[48.59.198.247] /opt/meteord/run_app.sh: line 36: 16 Killed node main.js
My app was very simple, but apparently not light-weight. My server/main.js looked like this:
Meteor.startup(function () {
My_LineItems.find({}, {fields: {targeting: 1, id: 1}}).observeChanges({
changed: function(_id, fields) {
update_targeting(fields.id, fields.targeting);
}
});
My_LineItems.find({}).observeChanges({
added: function(_id, fields) {
update_targeting(fields.id, fields.targeting);
}
});
console.log('The app should be started now...');
});
Apparently those requests to observe those queries were so slow that they would not allow the app to start and after the 15-second or 120-second deployCheckWaitTime the app had still not properly started.
I solved the issue by changing the code above to make it like this:
Meteor.startup(function () {
Meteor.setTimeout(function() {
My_LineItems.find({}, {fields: {targeting: 1, id: 1}}).observeChanges({
changed: function(_id, fields) {
update_targeting(fields.id, fields.targeting);
}
});
My_LineItems.find({}).observeChanges({
added: function(_id, fields) {
update_targeting(fields.id, fields.targeting);
}
});
}, 30);
console.log('The app should be started now...');
});
With this adjustment my app was able to deploy with not problem.
Basically, every time I deployed the app it had to run through the added method for every item in the collection, of which there were many. My putting this into a Meteor.setTimeout() I was able to get mupx to register the app as having started correctly and then the heavy process would just run in the background so to speak.
This was fixed for me by simply increasing the 'deployCheckWaitTime' in mup.json to 120 (I assume anything reasonably higher than the default 20 would work). Guess it just needed more time to process.
I've seen this resolved for others by using an instance with more RAM.