deploy nextjs app on firebase google cloud - javascript

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!

Related

Getting Error When Using Next.js With Jest

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"

Error: `experimental.runtime` requires `experimental.reactRoot` to be enabled along with React 18

I've a project with (next 12.1.6 + react 18.1 + react-dom 18.1). Now i want to add React Server Components to it. Updated my next.config.js like this
const nextConfig = {
distDir: '../../.next',
reactStrictMode: true,
experimental: {
runtime: 'nodejs',
serverComponents: true,
concurrentFeatures: true,
},
};
module.exports = nextConfig;
But regardless of that, when i execute npm run start:dev (npm run build works fine i believe) i get the error:
Error: `experimental.runtime` requires `experimental.reactRoot` to be enabled along with React 18. at Object.getBaseWebpackConfig [as default] (G:\ORLVNIcard\orlvni-business-card\node_modules\next\build\webpack-config.ts:355:11) at async Promise.all (index 0) at Span.traceAsyncFn (G:\ORLVNIcard\orlvni-business-card\node_modules\next\trace\trace.ts:106:14) at Span.traceAsyncFn (G:\ORLVNIcard\orlvni-business-card\node_modules\next\trace\trace.ts:106:14) at HotReloader.start (G:\ORLVNIcard\orlvni-business-card\node_modules\next\server\dev\hot-reloader.ts:518:21) at DevServer.prepare (G:\ORLVNIcard\orlvni-business-card\node_modules\next\server\dev\next-dev-server.ts:404:5) at ViewService.onModuleInit (G:\ORLVNIcard\orlvni-business-card\src\server\view\view.service.ts:19:7) at async Promise.all (index 0) at Object.callModuleInitHook (G:\ORLVNIcard\orlvni-business-card\node_modules\#nestjs\core\hooks\on-module-init.hook.js:43:5) at NestApplication.callInitHook (G:\ORLVNIcard\orlvni-business-card\node_modules\#nestjs\core\nest-application-context.js:169:13)
Next.js documentation says in https://nextjs.org/docs/advanced-features/react-18/server-components that i should use next#canary instead of next#12.1.6, and it works, but i have another problem with #canary in HookWebpackError: The "to" argument must be of type string. Received undefined and #12.1.6 does not throw the error in fresh barely empty project with (next 12.1.6 + react 18.1 + react-dom 18.1).
Part of my package.json looks like this
"scripts": {
"prebuild": "rimraf dist",
"build": "nest build && cd src/client && next build",
"format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
"start": "nest start",
"start:dev": "nest start --watch",
"start:debug": "nest start --debug --watch",
"start:prod": "node dist/main",
"lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix",
"test": "jest",
"typeorm": "node --require ts-node/register ./node_modules/typeorm/cli.js",
"test:watch": "jest --watch",
"test:cov": "jest --coverage",
"test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand",
"test:e2e": "jest --config ./test/jest-e2e.json"
},
"dependencies": {
"#nestjs/common": "^8.0.0",
"#nestjs/config": "^1.1.5",
"#nestjs/core": "^8.0.0",
"#nestjs/jwt": "^8.0.0",
"#nestjs/mongoose": "^9.0.2",
"#nestjs/passport": "^8.0.1",
"#nestjs/platform-express": "^8.0.0",
"#types/bcrypt": "^5.0.0",
"#types/mongoose": "^5.11.97",
"bcrypt": "^5.0.1",
"cookie-parser": "^1.4.6",
"dotenv": "^10.0.0",
"mongodb": "^4.3.1",
"mongoose": "^6.1.10",
"mssql": "^7.3.0",
"next": "^12.1.6",
"passport": "^0.4.1",
"passport-jwt": "^4.0.0",
"react": "18.1.0",
"react-dom": "18.1.0",
"reflect-metadata": "^0.1.13",
"rimraf": "^3.0.2",
"rxjs": "^7.2.0",
"sass": "^1.45.0",
"ts-node": "^10.0.0"
},
"devDependencies": {
"#nestjs/cli": "^8.0.0",
"#nestjs/schematics": "^8.0.0",
"#nestjs/testing": "^8.0.0",
"#types/cookie-parser": "^1.4.2",
"#types/express": "^4.17.13",
"#types/jest": "27.0.2",
"#types/node": "^16.0.0",
"#types/passport-jwt": "^3.0.6",
"#types/react": "^18.0.12",
"#types/react-dom": "^18.0.5",
"#types/supertest": "^2.0.11",
"#typescript-eslint/eslint-plugin": "^5.0.0",
"#typescript-eslint/parser": "^5.0.0",
"eslint": "^7.28.0",
"eslint-config-prettier": "^8.3.0",
"eslint-plugin-prettier": "^4.0.0",
"jest": "^27.2.5",
"prettier": "^2.3.2",
"source-map-support": "^0.5.20",
"supertest": "^6.1.3",
"ts-jest": "^27.0.3",
"ts-loader": "^9.2.3",
"ts-node": "^10.0.0",
"tsconfig-paths": "^3.10.1",
"typescript": "^4.3.5"
},
And this is how i start my next app
import { Injectable, OnModuleInit } from '#nestjs/common';
import { ConfigService } from '#nestjs/config';
import createServer from 'next';
import { NextServer } from 'next/dist/server/next';
import { Request, Response } from 'express';
#Injectable()
export class ViewService implements OnModuleInit {
private server: NextServer;
constructor(private configService: ConfigService) {}
async onModuleInit(): Promise<void> {
try {
this.server = createServer({
dev: this.configService.get<string>('NODE_ENV') !== 'production',
dir: './src/client',
});
await this.server.prepare();
} catch (error) {
console.error(error);
}
}
handler(req: Request, res: Response) {
return this.server.getRequestHandler()(req, res);
}
}
Guess the error is due to next somehow not seeing react 18 in #12.1.6, but i can't realize why, especially while in new project everything works fine.
Remove your package-lock.json and install the canary version of next
npm install next#canary react#latest react-dom#latest
Then add expermiental settings in your next.config.js
experimental: {
reactRoot: true,
runtime: "nodejs",
serverComponents: true,
concurrentFeatures: true
}
Apparently the error was thrown 'cause by default createServer() method of Next.js is creating react server with react 17 and old methods of react, like render(), hydrate() and so on. To make createServer() create react 18 server it's necessary to define __NEXT_REACT_ROOT as true in the environment of the process of our custom server. At least i've understood it this way. So the solution is
async onModuleInit(): Promise<void> {
process.env.__NEXT_REACT_ROOT = 'true';
try {
this.server = createServer({
dev: this.configService.get<string>('NODE_ENV') !== 'production',
dir: './src/client',
});
await this.server.prepare();
} catch (error) {
console.error(error);
}
}
It solved the problem for me.
Just add this line to your .env file and it will fix the issue
__NEXT_REACT_ROOT=true

Nuxt-ts, vuex error: This dependency was not found in .nuxt/store.js

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

Google App Engine: Modify Cloud Run Environment

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).

You seem to not be depending on "#angular/core". This is an error. Angular project

So I am trying the run the environment scripts and APIs for the development side of the website my team is building and every time I run ng build for each environment API this error pops up:
Example of the error that is being produced
now here is my pack.json file:
{
"name": "clark-gateway",
"version": "1.0.0-beta.4.0",
"description": "",
"main": "app.js",
"scripts": {
"start": "npm run gulp-tsc",
"build": "node_modules/.bin/gulp tsc",
"gulp-tsc": "node_modules/.bin/gulp start",
"lint": "node_modules/.bin/tslint --project ./src/**",
"pack": "npm run build && cp ./package.json ./dist && cd ./dist && zip -r ../dist.zip ./* & cd ..",
"zip": "cp ./package.json ./dist && cd ./dist && zip -r ../dist.zip ./* & cd ..",
"deploy": "eb deploy CLARK-Gateway-Production --label CLARK-Gateway-v$(node -p \"require('./package.json').version\")",
"document": "node_modules/.bin/typedoc --out ./docs/ ./src/"
},
"author": "",
"license": "ISC",
"devDependencies": {
"#types/express-jwt": "0.0.38",
"#types/jsonwebtoken": "^7.2.3",
"#types/raven": "^2.1.3",
"#types/request-promise": "^4.1.39",
"#types/express": "^4.0.39",
"#types/node": "^8.0.32",
"concurrently": "^3.5.0",
"gulp": "^3.9.1",
"gulp-nodemon": "^2.2.1",
"gulp-typescript": "^3.1.7",
"pre-commit": "^1.2.2",
"tslint": "^5.7.0",
"tslint-config-airbnb": "^5.3.0",
"typedoc": "^0.9.0",
"typescript": "^2.3.4"
},
"dependencies": {
"#cyber4all/clark-entity": "^2.1.0-beta.0.4",
"#cyber4all/clark-taxonomy": "^2.0.0",
"#types/socket.io": "^1.4.33",
"aws-sdk": "^2.147.0",
"body-parser": "^1.17.1",
"cookie-parser": "^1.4.3",
"cors": "^2.8.4",
"dotenv": "^4.0.0",
"express": "^4.15.2",
"express-http-proxy": "^1.1.0",
"express-jwt": "^5.3.0",
"helmet": "^3.6.1",
"jsonwebtoken": "^7.4.1",
"morgan": "^1.9.0",
"multer": "^1.3.0",
"ngx-cookie": "^2.0.1",
"raven": "^2.3.0",
"request": "^2.85.0",
"serverless-http": "^1.5.3",
"socket.io": "^2.1.0"
},
"pre-commit": [
"lint"
],
"prettier": {
"singleQuote": true,
"trailingComma": "all"
}
}
Things that I have tried:
- I have deleted the node modules folder numerous times (3 times to be exact)
- npm installed 3 times also deleted the pack-lock.json file
- Also I did the recommended commands and it gave me more errors such as
PS C:\Clark-Development\CLARK-Environment-master\cart-service> ng
build
Local workspace file ('angular.json') could not be found.
Error: Local workspace file ('angular.json') could not be found.
at WorkspaceLoader._getProjectWorkspaceFilePath (C:\Clark-Development\CLARK-Environment-master\cart-service\node_modules\#angular\cli\models\workspace-loader.js:37:19)
at WorkspaceLoader.loadWorkspace (C:\Clark-Development\CLARK-Environment-master\cart-service\node_modules\#angular\cli\models\workspace-loader.js:24:21)
at BuildCommand._loadWorkspaceAndArchitect (C:\Clark-Development\CLARK-Environment-master\cart-service\node_modules\#angular\cli\models\architect-command.js:180:32)
at BuildCommand. (C:\Clark-Development\CLARK-Environment-master\cart-service\node_modules\#angular\cli\models\architect-command.js:47:25)
at Generator.next ()
at C:\Clark-Development\CLARK-Environment-master\cart-service\node_modules\#angular\cli\models\architect-command.js:7:71
at new Promise ()
at __awaiter (C:\Clark-Development\CLARK-Environment-master\cart-service\node_modules\#angular\cli\models\architect-command.js:3:12)
at BuildCommand.initialize (C:\Clark-Development\CLARK-Environment-master\cart-service\node_modules\#angular\cli\models\architect-command.js:46:16)
at Object. (C:\Clark-Development\CLARK-Environment-master\cart-service\node_modules\#angular\cli\models\command-runner.js:87:23)
This error occurs after I execute the command npm install --save-dev #angular/core#latest
So it turns out I was running the wrong commands, which explains why its saying it needs angular-cli to use the command I was using. I used npm start which worked flawlessly

Categories

Resources