I'm trying to deploy a Next.js app which uses a custom Node.js server.
I want to inject custom build variables into the app:
next.config.js
const NODE_ENV = process.env.NODE_ENV;
const envType = NODE_ENV === `production` ? `production` : `staging`;
const envPath = `./config/${envType}`;
const { env } = require(envPath);
module.exports = {
env: { ...env },
};
The above file is run at build time (yarn build).
The issue is that Google App Engine uses Cloud Build behind the scenes. There, the NODE_ENV is always set to development. How can I override the NODE_ENV there; i.e. how can I customize the Cloud Build used for the Google App Engine gcloud app deploy?
I can't just use Docker because of this issue.
package.json
{
"name": "blah",
"version": "0.0.1",
"private": true,
"scripts": {
"dev": "NODE_ENV=staging node server.js",
"build": "rm -rf node_modules/ && yarn && rm -rf .next/ && next build",
"start": "node server.js",
"lint": "eslint . --ext .js",
"gcp-build": "yarn build"
},
"dependencies": {
"body-parser": "^1.18.3",
"dotenv": "^7.0.0",
"dotenv-webpack": "^1.7.0",
"express": "^4.16.4",
"express-session": "^1.16.1",
"firebase": "^5.10.0",
"firebase-admin": "^7.3.0",
"isomorphic-unfetch": "^3.0.0",
"lodash": "^4.17.11",
"next": "^8.1.0",
"now": "^15.0.6",
"react": "^16.8.6",
"react-dom": "^16.8.6",
"session-file-store": "^1.2.0",
"styled-components": "^4.2.0",
"yenv": "^2.1.0"
},
"devDependencies": {
"babel-eslint": "^10.0.1",
"eslint": "^5.16.0",
"eslint-config-airbnb": "^17.1.0",
"eslint-plugin-import": "^2.17.2",
"eslint-plugin-jsx-a11y": "^6.2.1",
"eslint-plugin-react": "^7.12.4"
},
"engines": {
"node": "10.x.x"
}
}
app.yaml
runtime: nodejs10
image
Below is the output of passing a DOGE_ENV variable from app.yaml. As you can see, it is undefined. However, NODE_ENV is development.
That is, adding the following to app.yaml does not work.
env_variables:
DOGE_ENV: production
Don't use NODE_ENV, create your own environment variable and use that:
App.yaml
env_variables:
ST_ENV: Production
next.config.js
const environment = process.env.ST_ENV;
const envType = environment === `production` ? `production` : `staging`;
const envPath = `./config/${envType}`;
const { env } = require(envPath);
module.exports = {
env: { ...env },
};
I had the same issue, at the end I solved setting NODE_ENV=production in the package.json script, so in your case just use:
{
"gcp-build": "NODE_ENV=production yarn build"
}
otherwise you can create a Cloud Build configuration file, check the docs, it supports an env section where you can define environmental variables
I had the same problem and ended up using an approach similar to Luca's answer, but with a mechanism to substitute the correct variable in package.json before the deploy (using the microsoft/variable-substitution GitHub action in my case).
Related
I am trying to run a test in next.js using jest, but i keep getting an error:
The error below may be caused by using the wrong test environment, see https://jestjs.io/docs/configuration#testenvironment-string. Consider using the "jsdom" test environment.
I have tried following the link and addding the docblock:
/**
* #jest-environment jsdom
*/
to my code with no success.
I have also tried configuring my jest.config.js based on the next.js testing page. This does not work I have tried both the solution with and without the rust compiler. Neither works:
Package.JSON:
{
"name": "chat",
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "next lint",
"test": "jest --env=node --forceExit --watchAll --coverage"
},
"dependencies": {
"#firebase/testing": "^0.20.11",
"firebase": "^9.9.4",
"kill-port": "^2.0.1",
"next": "12.2.5",
"react": "18.2.0",
"react-dom": "18.2.0",
"react-firebase-hooks": "^5.0.3",
"react-hot-toast": "^2.3.0",
"uuid": "^8.3.2"
},
"devDependencies": {
"#babel/plugin-syntax-jsx": "^7.18.6",
"#babel/preset-react": "^7.18.6",
"#firebase/rules-unit-testing": "^2.0.4",
"#testing-library/jest-dom": "^5.16.5",
"#testing-library/react": "^13.4.0",
"#types/jest": "^29.0.2",
"eslint": "8.23.0",
"eslint-config-next": "12.2.5",
"firebase-admin": "^11.0.1",
"jest": "^29.0.3",
"jest-environment-jsdom": "^29.0.3"
}
}
Jest.config.js:
// jest.config.js
const nextJest = require('next/jest');
const createJestConfig = nextJest({
// Provide the path to your Next.js app to load next.config.js and .env files in your test environment
dir: './',
});
// Add any custom config to be passed to Jest
/** #type {import('jest').Config} */
const customJestConfig = {
// Add more setup options before each test is run
// setupFilesAfterEnv: ['<rootDir>/jest.setup.js'],
// if using TypeScript with a baseUrl set to the root directory then you need the below for alias' to work
//moduleDirectories: ['node_modules', '<rootDir>/'],
testEnvironment: 'jest-environment-jsdom',
};
// createJestConfig is exported this way to ensure that next/jest can load the Next.js config which is async
module.exports = createJestConfig(customJestConfig);
test/page.test.js
import { render, screen } from '#testing-library/react';
import Home from '../pages/index';
describe('Home', () => {
it('renders a heading', () => {
render(<Home />);
expect(2 + 2).toBe(4);
});
});
You're overriding the env in your npm test script, remove --env=node:
"test": "jest --forceExit --watchAll --coverage"
OS: Windows 10
what am I already did
Delete .nuxt and run "yarn run dev": not work
Delete .nuxt and run "npm run dev": not work
Change node version to 16.15.1 and 14.19.3: not work
Team Repository, can not recreate the project.
I think because nuxtJS generate .nuxt/store.js with double back slash
but I can not force nuxtJS to use forward slash
ERROR Failed to compile with 1 errors friendly-errors 15:27:35
This dependency was not found: friendly-errors 15:27:35
friendly-errors 15:27:35
* ..\store\signIn.ts in ./.nuxt/store.js
/.nuxt/store.js
import Vue from "vue";
import Vuex from "vuex";
Vue.use(Vuex);
const VUEX_PROPERTIES = ["state", "getters", "actions", "mutations"];
let store = {};
(function updateModules() {
store = normalizeRoot(require("..\\store\\index.ts"), "store/index.ts");
// If store is an exported method = classic mode (deprecated)
if (typeof store === "function") {
return console.warn(
"Classic mode for store/ is deprecated and will be removed in Nuxt 3."
);
}
// Enforce store modules
store.modules = store.modules || {};
resolveStoreModules(require("..\\store\\auth.ts"), "auth.ts");
resolveStoreModules(require("..\\store\\profile.ts"), "profile.ts");
resolveStoreModules(require("..\\store\\signIn.ts"), "signIn.ts");
I don't know why it passes all require() to error at "..\store\signIn.ts"
/store/index.js
export const state = () => ({})
export const getters = {}
export const mutations = {}
export const actions = {}
/store/signIn.js
// /store/signIn.ts
import { getterTree, mutationTree, actionTree } from 'typed-vuex'
package.json
{
"name": "nuxt-web",
"version": "1.0.0",
"private": true,
"scripts": {
"dev": "nuxt-ts",
"build": "nuxt-ts build",
"generate": "nuxt-ts generate",
"start": "nuxt-ts start",
"lint": "eslint --ext .ts,.js,.vue .",
"lint:js": "eslint --ext \".js,.ts,.vue\" --ignore-path .gitignore .",
"lintfix": "npm run lint:js -- --fix"
},
"dependencies": {
"#nuxt/typescript-runtime": "^2.1.0",
"#nuxtjs/axios": "^5.13.6",
"#nuxtjs/dotenv": "^1.4.1",
"bootstrap": "^4.6.1",
"bootstrap-vue": "^2.21.2",
"core-js": "^3.19.3",
"nuxt": "^2.15.8",
"nuxt-property-decorator": "^2.9.1",
"nuxt-typed-vuex": "^0.3.0",
"nuxt-web3": "^0.0.8",
"vue": "^2.6.14",
"vue-class-component": "^7.2.6",
"vue-server-renderer": "^2.6.14",
"vue-template-compiler": "^2.6.14",
"webpack": "^4.46.0"
},
"devDependencies": {
"#babel/eslint-parser": "^7.16.3",
"#nuxt/types": "^2.15.8",
"#nuxt/typescript-build": "^2.1.0",
"#nuxtjs/eslint-config-typescript": "^8.0.0",
"#nuxtjs/eslint-module": "^3.0.2",
"#nuxtjs/vercel-builder": "^0.21.3",
"#types/vuelidate": "^0.7.15",
"eslint": "^8.4.1",
"eslint-plugin-nuxt": "^3.1.0",
"eslint-plugin-vue": "^8.2.0",
"typescript": "^4.6.3",
"vuelidate": "^0.7.7"
}
}
it's my first question, apologies if it unclear
The issue got resolved after doing this
change node version to 12.17.0
remove .next
remove node_modules
npm install
npm run dev
im stuck trying to work with a js library (ifc.js) inside my django project, I installed django-compressor and django-compressor-toolkit with default values, ifc.js uses rollup to bundle files, the npm package conf file is
{
"name": "a_viurb",
"version": "1.0.0",
"description": "funcionamiento ifc js",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build": "rollup -c ./a_viurb/static/ifc/rollup.config.js",
"watch": "rollup -w -c ./a_viurb/static/ifc/rollup.config.js"
},
"author": "fcr",
"license": "ISC",
"devDependencies": {
"#babel/core": "^7.17.9",
"#babel/preset-env": "^7.16.11",
"#babel/preset-react": "^7.16.7",
"#rollup/plugin-node-resolve": "^13.1.3",
"autoprefixer": "^7.1.2",
"babel-core": "^6.26.3",
"babel-loader": "^8.2.4",
"babel-preset-es2015": "^6.24.1",
"babelify": "^7.3.0",
"browserify": "^14.5.0",
"css-loader": "^6.7.1",
"node-sass": "^4.14.1",
"postcss-cli": "^4.1.0",
"rollup": "^2.70.1",
"webpack": "^5.72.0",
"webpack-cli": "^4.9.2"
},
"dependencies": {
"three": "^0.139.2",
"web-ifc-three": "0.0.110"
},
"presets": [
"#babel/preset-env",
"#babel/preset-react"
]
}
my settings.py configuration
STATICFILES_FINDERS = (
'compressor.finders.CompressorFinder',
)
COMPRESS_CSS_FILTERS = [
'compressor.filters.css_default.CssAbsoluteFilter',
'compressor.filters.cssmin.CSSMinFilter',
'compressor.filters.template.TemplateFilter'
]
COMPRESS_JS_FILTERS = [
'compressor.filters.jsmin.JSMinFilter',
]
COMPRESS_PRECOMPILERS = (
('module', 'compressor_toolkit.precompilers.ES6Compiler'),
('css', 'compressor_toolkit.precompilers.SCSSCompiler'),
)
COMPRESS_LOCAL_NPM_INSTALL = True
and i got these error message
SyntaxError: /home/fcr/anaconda3/envs/gda/a_viurb/a_viurb/static/ifc/bundle.js: Unexpected token (87230:6)
87228 | throw new Error(nullIfcManagerErrorMessage);
87229 | const modelConfig = {
> 87230 | ...config,
| ^
87231 | modelID: this.modelID
it seems like a pre compiling error, not recognizing the spread operator, I dont know how to approach this, how to fix babel configuration or the required requirements, is there another way to make js buldles work in django?, or only load the this kind of js files?
thanks
I fuound a way to make it work
install memcached
sudo apt-get install memcached
(env install) pip install python-memcached
(env install) pip install django-htmlmin
settings.py
CACHES = {
'default': {
'BACKEND':
'django.core.cache.backends.memcached.MemcachedCache',
'LOCATION': '127.0.0.1:11211',
}
}
MIDDLEWARE = [
# add these below 3 middleware at the first position
'django.middleware.gzip.GZipMiddleware',
'htmlmin.middleware.HtmlMinifyMiddleware',
'htmlmin.middleware.MarkRequestMiddleware',
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
'compressor.finders.CompressorFinder',
)
remove django compressor toolkit configuration and add this
COMPRESS_ENABLED = True
COMPRESS_CSS_HASHING_METHOD = 'content'
COMPRESS_FILTERS = {
'css':[
'compressor.filters.css_default.CssAbsoluteFilter',
'compressor.filters.cssmin.rCSSMinFilter',
],
'js':[
'compressor.filters.jsmin.JSMinFilter',
]
}
HTML_MINIFY = True
KEEP_COMMENTS_ON_MINIFYING = True
I am trying to get jest to work with a new react-native project. However, when I run npm run test, I get the following error ReferenceError: __DEV__ is not defined. I've looked through countless Github issues and Stack Overflow posts regarding this but none of the suggestions have worked in my case.
Here is my jest.config.js file:
module.exports = {
transformIgnorePatterns: [
"node_modules/(?!(react-native|react-native-button|react-native-video)/)"
],
setupFiles: ['<rootDir>/__tests__/setup.json'],
}
package.json (notice I added DEV = true inside "jest")
{
"name": "DigitalSignagePlayer",
"version": "0.0.1",
"private": true,
"scripts": {
"android": "react-native run-android",
"ios": "react-native run-ios",
"start": "react-native start",
"test": "jest",
"lint": "eslint ."
},
"dependencies": {
"#react-native-async-storage/async-storage": "^1.15.5",
"axios": "^0.21.1",
"react": "^17.0.1",
"react-native": "0.64.2",
"react-native-fs": "^2.18.0",
"react-native-splash-screen": "^3.2.0",
"react-native-video": "^5.1.1"
},
"devDependencies": {
"#babel/core": "^7.14.5",
"#babel/preset-env": "^7.14.7",
"#babel/runtime": "^7.14.5",
"#react-native-community/eslint-config": "^2.0.0",
"babel-jest": "^27.0.2",
"eslint": "^7.28.0",
"jest": "^27.0.5",
"metro-react-native-babel-preset": "^0.66.0",
"react-test-renderer": "17.0.1"
},
"jest": {
"preset": "react-native",
}
}
bable.config.js
module.exports = {
presets: ['module:metro-react-native-babel-preset', '#babel/preset-env'],
};
metro.config.js
/**
* Metro configuration for React Native
* https://github.com/facebook/react-native
*
* #format
*/
module.exports = {
transformer: {
getTransformOptions: async () => ({
transform: {
experimentalImportSupport: false,
inlineRequires: true,
},
}),
},
};
I have tried setting globals.DEV = true and global.DEV = true at the top of my test files. I have tried adding setupFiles to jest.config.js which loads a setup.js file that contains global.DEV = true too. I have tried updating jest also. My current version of react-native is:
react-native-cli: 2.0.1
react-native: 0.64.2
I'm also using Metro, not Expo and I initially created the app with react-native-cli.
UPDATE:
setup.json
{
"globals": { "__DEV__": true }
}
UPDATE 2:
I changed setup.json to setup.js but I am still getting the same error:
global.__DEV__ = true
The variable is called __DEV__, so using DEV by trial and error doesn't make sense. Setting it in tests won't help because it won't affect the usage of the variable on import. In order to do this, this should have been done before tests in setupFiles* files.
Jes globals configuration option is supposed to do this. There should be "globals": { "__DEV__": true }. The configuration in package.json overridden by the configuration in jest.config.js. There should be only one of them (likely the latter), the other one needs to be removed.
I am thinking of deploying nextjs project on gcp firebase. However, I could not see any pages running. I mean it's shown fully blank. I am not quite sure if I missed something for deployment.
Here is my configuration
.next
public
src
pages
components
assets - images
server.js
.babelrc
.env.development
.env.staging
.env.production
.firebaserc
firebase.json
jsconfig.json
next.config.js
Now the setup for deployment
firebase.json
{
"hosting": {
"public": "public",
"ignore": ["firebase.json", "**/.*", "**/node_modules/**"],
"rewrites": [
{
"source": "**/**",
"function": "next"
}
]
},
"functions": {
"source": ".",
"ignore": [
".firebase/**",
".firebaserc",
"firebase.json",
"**/node_modules/**",
"**/.vscode/**",
"**/conventions/**",
"**/.hooks/**",
"**/public/**"
]
}
}
.firebaserc
{
"projects": {
"default": "jeweltrek-test"
}
}
next.config.js
const withPlugins = require("next-compose-plugins");
const optimizedImages = require("next-optimized-images");
const withPWA = require("next-pwa");
module.exports = withPlugins(
[optimizedImages],
[
withPWA({
pwa: {
dest: "public",
},
}),
]
);
server.js
const functions = require('firebase-functions');
const next = require('next');
var dev = process.env.NODE_ENV !== 'production';
var app = next({ dev, conf: { distDir: '.next' } });
var handle = app.getRequestHandler();
exports.next = functions.https.onRequest((req, res) => {
console.log('File: ' + req.originalUrl); // log the page.js file that is being requested
return app.prepare().then(() => handle(req, res));
});
package.json
{
"name": "jeweltrek-next",
"version": "0.1.0",
"private": true,
"main": "server.js",
"engines": {
"node": "10"
},
"scripts": {
"dev:client": "next",
"dev:server": "node src/server --source-maps --watch",
"dev": "dotenv -e .env.development yarn dev:client & yarn dev:server",
"build": "dotenv -e .env.production next build",
"build:staging": "dotenv -e .env.staging next build",
"serve": "dotenv -e .env.staging firebase serve --only functions,hosting",
"deploy": "dotenv -e .env.staging firebase deploy --only functions,hosting",
"start": "next start"
},
"dependencies": {
"apollo-boost": "^0.4.7",
"dotenv": "^8.2.0",
"express": "^4.17.1",
"firebase-admin": "^8.12.1",
"firebase-functions": "^3.6.1",
"formik": "^2.1.4",
"graphql": "^15.0.0",
"html-to-draftjs": "^1.5.0",
"imagemin-mozjpeg": "^8.0.0",
"imagemin-optipng": "^7.1.0",
"isomorphic-fetch": "^2.2.1",
"isomorphic-unfetch": "^3.0.0",
"lodash": "^4.17.15",
"lqip-loader": "^2.2.0",
"next": "^9.4.0",
"next-compose-plugins": "^2.2.0",
"next-optimized-images": "^2.5.8",
"next-pwa": "^2.4.1",
"next-runtime-dotenv": "^1.2.0",
"nprogress": "^0.2.0",
"react": "16.13.1",
"react-apollo": "^3.1.5",
"react-apollo-hooks": "^0.5.0",
"react-dom": "16.13.1",
"react-draft-wysiwyg": "^1.14.4",
"styled-components": "^5.1.0",
"webp-loader": "^0.6.0",
"yup": "^0.28.3"
},
"devDependencies": {
"babel-eslint": "^10.1.0",
"firebase-functions-test": "^0.2.1"
}
}
for deploying what I am doing is
First i build file using yarn build:staging if its for staging
yarn deploy
it says deployment complete as well with no error but if i navigate to the browser then it does not render the pages
https://us-central1-jeweltrek-test.cloudfunctions.net/next/
this is what i get
It could be something related to permissions to cloud functions and IAM or authentication, check this page: https://firebase.google.com/docs/reference/fcm/rest/v1/ErrorCode
Also, check this answer:
Firebase Functions HTTPS 403 Forbidden
I hope this solves it. Good Luck!