I'm running my firebase project and got this error in the terminal
This dependency was not found:
firebase in ./src/firebaseInit.js
To install it, you can run: npm install --save firebase
Error from chokidar (C:): Error: EBUSY: resource busy or locked, lstat 'C:\DumpStack.log.tmp
inside my firebaseInit.js
import firebase from 'firebase';
const firebaseConfig = {
apiKey: "xxxxxxxxxxxxxx",
authDomain: "xxxxxxxxxxxxxxxxxxx",
projectId: "xxxxxxxxxxxxxxxxxxxxxxxx",
storageBucket: "xxxxxxxxxxxxxxxxxx",
messagingSenderId: "xxxxxxxxxxxxxxxxxxxxxx",
appId: "xxxxxxxxxxxxxxxxxxxxxxxxxx",
measurementId: "xxxxxxxxxxxxxxxxxx"
};
export default firebase.initializeApp(firebaseConfig);
and here's my package.json
{
"name": "mevnproject",
"version": "0.1.0",
"private": true,
"scripts": {
"serve": "vue-cli-service serve",
"build": "vue-cli-service build",
"lint": "vue-cli-service lint"
},
"dependencies": {
"axios": "^0.25.0",
"core-js": "^3.6.5",
"firebase": "9.6.11",
"socket.io": "^4.4.1",
"vue": "^2.6.11",
"vue-chat-scroll": "^1.4.0",
"vue-google-charts": "^0.3.3",
"vue-router": "^3.5.3",
"vue2-google-maps": "^0.10.7",
"vuetify": "^2.6.2",
"vuex": "^3.6.2",
"vuex-persistedstate": "^4.1.0"
},
"devDependencies": {
"#mdi/font": "^6.5.95",
"#mdi/js": "^6.5.95",
"#vue/cli-plugin-babel": "~4.5.0",
"#vue/cli-plugin-eslint": "~4.5.0",
"#vue/cli-service": "~4.5.0",
"babel-eslint": "^10.1.0",
"eslint": "^6.7.2",
"eslint-plugin-vue": "^6.2.2",
"material-design-icons-iconfont": "^6.1.1",
"vue-template-compiler": "^2.6.11"
},
"eslintConfig": {
"root": true,
"env": {
"node": true
},
"extends": [
"plugin:vue/essential",
"eslint:recommended"
],
"parserOptions": {
"parser": "babel-eslint"
},
"rules": {}
},
"browserslist": [
"> 1%",
"last 2 versions",
"not dead"
]
}
I tried to uninstall and reinstall the firebase but still got the same error.
edit: in my components i've the script looks like this
<script>
import { db } from "../../firebaseInit";
export default {
data() {
return {
message: null,
};
},
methods: {
saveMessage() {
db.firestore()
.collection("chat")
.add({
message: this.message,
})
.then(() => {
console.log("Document Written");
})
.catch((error) => {
console.error(error);
});
},
},
};
</script>
From your package.json file we can see that you use the Firebase SDK version 9. You therefore need to adapt your firebaseInit.js file. I recommend exporting only the services you need, i.e. Firestore in your case (see your comment below).
import { initializeApp } from "firebase/app";
import { getFirestore } from "firebase/firestore";
const firebaseConfig = {
apiKey: "xxxxxxxxxxxxxx",
authDomain: "xxxxxxxxxxxxxxxxxxx",
projectId: "xxxxxxxxxxxxxxxxxxxxxxxx",
storageBucket: "xxxxxxxxxxxxxxxxxx",
messagingSenderId: "xxxxxxxxxxxxxxxxxxxxxx",
appId: "xxxxxxxxxxxxxxxxxxxxxxxxxx",
measurementId: "xxxxxxxxxxxxxxxxxx"
};
const firebaseApp = initializeApp(firebaseConfig);
const db = getFirestore(firebaseApp);
export { db };
Then, in your component you do like:
import { db } from '../firebaseInit';
import { collection, addDoc } from 'firebase/firestore'; // Example
export default {
data() {
return {
message: null,
};
},
methods: {
saveMessage() {
addDoc(collection(db, 'chat'),
{
message: this.message,
})
.then(() => {
console.log("Document Written");
})
.catch((error) => {
console.error(error);
});
},
},
};
If you need to use several services, do as follows (for example):
import { initializeApp } from "firebase/app";
import { getFirestore } from "firebase/firestore";
import { getAuth } from "firebase/auth";
import { getStorage } from "firebase/storage";
const firebaseConfig = {
apiKey: "xxxxxxxxxxxxxx",
authDomain: "xxxxxxxxxxxxxxxxxxx",
projectId: "xxxxxxxxxxxxxxxxxxxxxxxx",
storageBucket: "xxxxxxxxxxxxxxxxxx",
messagingSenderId: "xxxxxxxxxxxxxxxxxxxxxx",
appId: "xxxxxxxxxxxxxxxxxxxxxxxxxx",
measurementId: "xxxxxxxxxxxxxxxxxx"
};
const firebaseApp = initializeApp(firebaseConfig);
const db = getFirestore(firebaseApp);
const auth = getAuth(firebaseApp);
const storage = getStorage(firebaseApp);
export { db, storage, auth };
and in the component
import { db, auth } from '../firebaseInit';
import { doc, getDoc } from 'firebase/firestore'; // Example
import { signInWithEmailAndPassword } from '#firebase/auth'; // Example
More details in the doc.
Related
I'm new to NextJS and Next-Auth.
I'm trying to write a secure api route that is only available if a user is logged in.
I sucessfully accessing the session on the client side using useSession() but when I try to implement the logic in an api route the session always returns null.
I have tried to copy the simpliest example from the docs. Am I missing something?
Here is my route in src/pages/api/users/getUser.ts:
import { getServerSession } from 'next-auth/next'
import { authOptions } from '../auth/[...nextauth]'
import { NextApiRequest, NextApiResponse } from 'next'
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
const session = await getServerSession(req, res, authOptions)
console.log('session', session)
if (session) {
res.send({ content: 'SUCCESS' })
} else {
res.send({ error: 'ERROR' })
}
}
Here is my authOptions in src/pages/api/auth/[...nextauth].ts
import NextAuth from 'next-auth'
import GithubProvider from 'next-auth/providers/github'
import { PrismaAdapter } from '#next-auth/prisma-adapter'
import prisma from '../../../../prisma/db/prismadb'
export const authOptions = {
adapter: PrismaAdapter(prisma),
providers: [
GithubProvider({
clientId: process.env.GITHUB_ID || '',
clientSecret: process.env.GITHUB_SECRET || '',
}),
],
pages: {
signIn: '/',
signOut: '/',
},
}
export default NextAuth(authOptions)
Here are my dependencies:
"dependencies": {
"#next-auth/prisma-adapter": "^1.0.5",
"#next/font": "13.1.6",
"#prisma/client": "^4.10.1",
"#types/node": "18.11.19",
"#types/react": "18.0.27",
"#types/react-dom": "18.0.10",
"axios": "^1.3.2",
"dotenv-cli": "^7.0.0",
"eslint": "8.33.0",
"eslint-config-next": "13.1.6",
"next": "13.1.6",
"next-auth": "^4.19.2",
"prisma": "^4.9.0",
"react": "18.2.0",
"react-dom": "18.2.0",
"styled-components": "^5.3.6",
"typescript": "4.9.5"
},
"devDependencies": {
"#types/styled-components": "^5.1.26"
}
In my case, when NEXTAUTH_URL is 127.0.0.1 and API is requested to localhost, the session is null.
So, I solved the problem by matching the NEXTAUTH_URL with the request URL.
If I generate production js bundle in my next.js project, it's not minified.
For example white characters are not removed.
package.json
{
"name": "web",
"version": "0.1.0",
"private": true,
"scripts": {
"web": "cross-env NODE_ENV=development node server.js",
"dev": "next",
"devServer": "node server.js",
"build": "next build",
"start": "next start"
},
"dependencies": {
"#zeit/next-css": "^1.0.1",
"apollo-boost": "^0.4.4",
"apollo-upload-client": "^11.0.0",
"body-parser": "^1.19.0",
"cross-env": "^6.0.3",
"express": "^4.17.1",
"graphql": "^14.5.8",
"intl": "^1.2.5",
"js-cookie": "^2.2.1",
"js-cookies": "^1.0.4",
"lodash.chunk": "^4.2.0",
"next": "9.1.2",
"next-cookies": "^2.0.3",
"next-with-apollo": "^4.3.0",
"optimize-css-assets-webpack-plugin": "^6.0.0",
"react": "16.11.0",
"react-apollo": "^3.1.3",
"react-dom": "16.11.0",
"react-image-lightbox": "^5.1.1",
"react-input-range": "^1.3.0",
"react-intl": "^3.6.1",
"react-modal": "^3.11.1",
"react-perfect-scrollbar": "^1.5.3",
"react-slick": "^0.25.2",
"slick-carousel": "^1.8.1"
},
"devDependencies": {
"babel-eslint": "^10.1.0",
"eslint": "^7.25.0",
"eslint-config-airbnb": "^18.2.1",
"eslint-plugin-import": "^2.22.1",
"eslint-plugin-jsx-a11y": "^6.4.1",
"eslint-plugin-react": "^7.23.2",
"eslint-plugin-react-hooks": "^4.2.0"
}
}
next.config.js
const withCSS = require("#zeit/next-css");
const OptimizeCSSAssetsPlugin = require("optimize-css-assets-webpack-plugin");
module.exports = withCSS({
webpack(config, options) {
config.optimization.minimizer = [];
config.optimization.minimizer.push(new OptimizeCSSAssetsPlugin({}));
return config;
},
distDir: "build",
});
server.js
const express = require('express');
const next = require('next');
const bodyParser = require("body-parser");
const dev = process.env.NODE_ENV !== undefined;
var app;
if(dev){
app = next({ dev});
}else{
app = next({ dev,conf:{
distDir: 'build'
} });
}
const handle = app.getRequestHandler();
app.prepare().then(() => {
const server = express();
server.use('/Public', express.static(__dirname + '/Public'));
server.use('/.well-known', express.static(__dirname + '/Public'));
server.use(bodyParser.urlencoded({ extended: false }));
server.use(bodyParser.json());
server.get('/', (req, res) => {
return app.render(req, res, '/index');
});
server.get('/robots.txt', (req, res) => {
return app.render(req, res, '/robots');
});
server.get('/sitemap.xml', (req, res) => {
return app.render(req, res, '/sitemap');
});
server.listen(8890, err => {
if (err) throw err
console.log('> Ready on http://localhost:8890')
})
})
If I run npm run build, dev variable in server.js is false.
The issue is on line:
config.optimization.minimizer = [];
Removing this line, minification works.
I have Gulp + Browsersync working with Wordpress.
Everything was working well, reloading every time I change files.
But since yesterday only, Browsersync keeps reloading without any reason.
I didn't made any changes on my gulpfile. I tried reverting to a former commit from 2 days ago, same thing. I don't know where it comes from.
Here's my repo.
I tried :
downgrading browsersync to 2.24.4 from this post
adding this to gulp :
socket: {
clients: {
heartbeatTimeout: 60000
}
},
Here are my files.
gulpfile.babel.js
import { src, dest, watch, series, parallel } from 'gulp';
import yargs from 'yargs';
import sass from 'gulp-sass';
import cleanCss from 'gulp-clean-css';
import gulpif from 'gulp-if';
import postcss from 'gulp-postcss';
import sourcemaps from 'gulp-sourcemaps';
import autoprefixer from 'autoprefixer';
import imagemin from 'gulp-imagemin';
import del from 'del';
import webpack from 'webpack-stream';
import named from 'vinyl-named';
import browserSync from 'browser-sync';
import zip from 'gulp-zip';
import info from './package.json';
import replace from 'gulp-replace';
import wpPot from 'gulp-wp-pot';
import tailwindcss from 'tailwindcss';
// import purgeCss from 'gulp-purgecss';
const PRODUCTION = yargs.argv.prod;
export const clean = () => del(['dist']);
export const styles = () => {
return (
src('src/scss/app.scss')
.pipe(gulpif(!PRODUCTION, sourcemaps.init()))
.pipe(sass().on('error', sass.logError))
.pipe(postcss([tailwindcss('./tailwind.config.js')]))
.pipe(gulpif(PRODUCTION, postcss([autoprefixer])))
.pipe(gulpif(PRODUCTION, cleanCss({ compatibility: 'ie8' })))
// .pipe(
// gulpif(
// PRODUCTION,
// purgeCss({
// content: ['**/*.php']
// })
// )
// )
.pipe(gulpif(!PRODUCTION, sourcemaps.write()))
.pipe(dest('dist/css'))
.pipe(server.stream())
);
};
export const images = () => {
return src('src/images/**/*.{jpg,jpeg,png,svg,gif}')
.pipe(gulpif(PRODUCTION, imagemin()))
.pipe(dest('dist/images'));
};
export const copy = () => {
return src(['src/**/*', '!src/{images,js,scss}', '!src/{images,js,scss}/**/*']).pipe(
dest('dist')
);
};
export const watchForChanges = () => {
watch('src/scss/**/*.scss', styles);
watch('src/images/**/*.{jpg,jpeg,png,svg,gif}', series(images, reload));
watch(['src/**/*', '!src/{images,js,scss}', '!src/{images,js,scss}/**/*'], series(copy, reload));
watch('src/js/**/*.js', series(scripts, reload));
watch('**/*.php', reload);
};
export const scripts = () => {
return src(['src/js/bundle.js'])
.pipe(named())
.pipe(
webpack({
module: {
rules: [
{
test: /\.js$/,
use: {
loader: 'babel-loader',
options: {
presets: ['#babel/preset-env']
}
}
}
]
},
mode: PRODUCTION ? 'production' : 'development',
devtool: !PRODUCTION ? 'inline-source-map' : false,
output: {
filename: '[name].js'
}
})
)
.pipe(dest('dist/js'));
};
/***** Generating a POT file *****/
export const pot = () => {
return src('**/*.php')
.pipe(
wpPot({
domain: 'boosters',
package: info.name
})
)
.pipe(dest(`languages/${info.name}.pot`));
};
/***** Compress theme into a ZIP file after renaming _themename *****/
export const compress = () => {
return src([
'**/*',
'!node_modules{,/**}',
'!bundled{,/**}',
'!src{,/**}',
'!.babelrc',
'!.gitignore',
'!gulpfile.babel.js',
'!package.json',
'!package-lock.json'
])
.pipe(
gulpif(
// prevent bug if there are zip files inside the theme
file => file.relative.split('.').pop() !== 'zip',
replace('boosters', info.name)
)
)
.pipe(zip(`${info.name}.zip`))
.pipe(dest('bundled'));
};
/****** BrowserSync ******/
const server = browserSync.create();
export const serve = done => {
server.init({
proxy: 'localhost:8888/boosters', // put your local website link here
snippetOptions: {
ignorePaths: 'boosters/wp-admin/**'
},
ghostMode: false
// socket: {
// clients: {
// heartbeatTimeout: 60000
// }
// },
// logLevel: 'debug',
// logFileChanges: true,
// logConnections: true
});
done();
};
export const reload = done => {
server.reload();
done();
};
/****** Series & Parallel Scripts ******/
export const dev = series(clean, parallel(styles, images, scripts, copy), serve, watchForChanges);
export const build = series(clean, parallel(styles, images, scripts, copy), pot, compress);
export default dev;
package.json
{
"name": "boosters",
"version": "1.0.0",
"description": "A Wordpress website for Boost.rs by DoubleCat Studio",
"main": "gulpfile.babel.js",
"scripts": {
"start": "gulp",
"build": "gulp build --prod"
},
"repository": {
"type": "git",
"url": "git+ssh://git#github.com/indaviande/boosters.git"
},
"author": "Vianney Bernet",
"license": "ISC",
"bugs": {
"url": "https://github.com/indaviande/boosters/issues"
},
"browserslist": [
"last 4 version",
"> 1%",
"ie 11"
],
"homepage": "https://github.com/indaviande/boosters#readme",
"devDependencies": {
"#babel/core": "^7.4.3",
"#babel/preset-env": "^7.4.3",
"#babel/register": "^7.4.0",
"autoprefixer": "^9.5.1",
"babel-loader": "^8.0.5",
"browser-sync": "^2.26.7",
"del": "^4.1.0",
"gulp": "^4.0.0",
"gulp-clean-css": "^4.0.0",
"gulp-if": "^2.0.2",
"gulp-imagemin": "^5.0.3",
"gulp-postcss": "^8.0.0",
"gulp-replace": "^1.0.0",
"gulp-sass": "^4.0.2",
"gulp-sourcemaps": "^2.6.5",
"gulp-wp-pot": "^2.3.5",
"gulp-zip": "^4.2.0",
"tailwindcss": "^1.0.4",
"vinyl-named": "^1.1.0",
"webpack-stream": "^5.2.1",
"yargs": "^13.2.2"
},
"dependencies": {
"tar": ">4.4.7"
}
}
Browsersync has a log that you can inspect to see which files are being changed that trigger the reload. You can also increase specificity of what you're watching/ignoring. Start off small and gradually increase your glob paths until you can see reloads on all changes.
server.init({
logLevel: 'debug',
files: [
'wp-content/themes/**/*.css',
'wp-content/themes/**/*.js',
'wp-content/themes/**/*.php',
],
ignore: [
'folder-to-ignore/**/*.*'
]
});
I am getting this error when trying to use #google-cloud/logging with Firebase Functions. If I remove the logging stuff everything works fine. I also tried using #google-cloud/logging-winston however, causing the same error along with an additional error.
Here is my code:
const functions = require('firebase-functions')
const mongoose = require('mongoose')
const Tag = require('../../models/tag')
const { Logging } = require('#google-cloud/logging')
const logging = new Logging({projectId: 'circle-fc687'})
const log = logging.log('tags')
const METADATA = {
resource: {
type: 'cloud_function',
labels: {
function_name: 'tags-getTags',
region: 'us-central1'
}
}
}
const uri = 'mongoURL'
module.exports = functions.https.onRequest(async (req, res) => {
try {
console.log('getTags : start')
const logOne = log.entry(METADATA, { event: 'getTags:mongodb:started', value: 'started', message: 'tags-getTags:started' })
log.write(logOne) // I've also tried with an await here thinking maybe it was trying to do something after the function terminates but that didn't fix anything
console.log('getTags : after first logging statement') // doesn't work
await mongoose.connect(uri, { useNewUrlParser: true, useUnifiedTopology: true })
const result = await Tag.find({})
res.send(result)
} catch (err) {
res.send(err)
}
})
Here is the error:
Error: Could not load the default credentials. Browse to https://cloud.google.com/docs/authentication/getting-started for more information.
at GoogleAuth.getApplicationDefaultAsync (/srv/node_modules/google-auth-library/build/src/auth/googleauth.js:161:19)
at <anonymous>
at process._tickDomainCallback (internal/process/next_tick.js:229:7)
Edit 1: adding package.json
{
"name": "functions",
"description": "Cloud Functions for Firebase",
"scripts": {
"lint": "eslint .",
"serve": "firebase serve --only functions",
"shell": "firebase functions:shell",
"start": "npm run shell",
"deploy": "firebase deploy --only functions",
"logs": "firebase functions:log"
},
"engines": {
"node": "10"
},
"dependencies": {
"#google-cloud/logging": "^6.0.0",
"#google-cloud/logging-winston": "^3.0.2",
"axios": "^0.19.0",
"cors": "^2.8.5",
"firebase-admin": "^8.9.0",
"firebase-functions": "^3.3.0",
"mongoose": "^5.8.3",
"mongoose-unique-validator": "^2.0.3",
"winston": "^3.2.1"
},
"devDependencies": {
"eslint": "^5.12.0",
"eslint-plugin-promise": "^4.0.1",
"firebase-functions-test": "^0.1.7"
},
"private": true
}
I'm stuck at this error. I'm beginner in react native and firebase. I just want to make a connection between react native and firebase.
Please anyone has an idea about this problem?
index.android.js
/**
* Sample React Native App
* https://github.com/facebook/react-native
* #flow
*/
import React, {Component} from 'react';
import ReactNative from 'react-native';
import * as firebase from 'firebase';
const StatusBar = require('./components/StatusBar');
const ActionButton = require('./components/ActionButton');
const ListItem = require('./components/ListItem');
const styles = require('./styles.js')
// Initialize Firebase
firebase.intializeApp({
apiKey: "XXXX",
authDomain: "XXXX",
databaseURL: "XXXX",
projectId: "XXXX",
storageBucket: "XXXX",
messagingSenderId: "XXXX"
});
Package.js
{
"name": "Primed_Network",
"version": "0.2.0",
"private": true,
"scripts": {
"start": "node node_modules/react-native/local-cli/cli.js start",
"test": "jest"
},
"dependencies": {
"apsl-react-native-button": "^3.1.0",
"firebase": "^3.1.0",
"react": "16.0.0-alpha.12",
"react-native": "0.47.1",
"react-native-firebase": "^2.1.2",
"react-native-textinput-effects": "^0.4.0",
"react-native-vector-icons": "^4.3.0"
},
}
Try to import firebase like this
import firebase from 'firebase';