This story is inspired by another tutorial written by David, I strongly recommend to read of his Story and Github. Most of the content here are based on his work.
Best way to understand what happening in programing, is looking at the code. This pull-request is setting up Facebook and Google accounts login, build on top of the Vue template generated by vue-cli vuetifyjs/nuxt.
If you are looking for a ready cooked boilerplate for quick development, then clone this Repo, and set up the Firebase key, secrete in the config here ./services/fireinit.js
.
Firebase have done a very great job in authentication for the developers, great SDK, and great integration. Facebook, Google could be implemented just within few clicks on browser.
However, data in Firebase Web application is mostly happened on the browser, think about that, all the Facebook login pages, login popup is all about opening pages and redirecting pages, nothing to do with our awesome APIs. One of the challenge of using Firebase authentication on SSR architect (Nuxt.js) is understanding how the data flow goes in deep, carrying data from the browser to web server is a bit complex, topics such as Vuex, middleware, express-middleware and nuxt-plugin can not miss.
Authorize Firebase domain via your Firebase Console in Authentication settings via your Firebase Console under the Sign-In Methods Tab.
Connecting Firebase and Facebook
nuxt.config.js
Using SPA mode with Nuxt.js which is implemented by setting the option mode: 'spa'
in nuxt.config.js
.
To setup/initialize the firebase app with credentials, I created services/fireinit.js
.
Set up Firebase service in Nuxt
Firebase provides onAuthStateChanged
to handle user state. I created plugins/fireauth.js
to setup this functionality
Handling User Authentication State
Scenario 1: A user is already signed-in and the next route is /login
Redirect to _/admin_
Scenario 2: There is not a user signed-in and the next route is /admin
Redirect to _/login_
Protecting Authenticated Routes
We will tell Nuxt.js to use this file by declaring it in nuxt.config.js
as follows:
With all of this in place, we are able to use Firebase Authentication with Nuxt.js to protect the /admin
route
This component is triggering action signInWithFacebook
, by calling this.$store.dispatch
Set up component FacebookLogin.vue
Setup action and store for Facebook Login Action
Basically, everything is setup within the above 8 steps.
When you open the page
localhost:3000/admin
, you are redirected tolocalhost:3000/login to
require login
When you open the page
_localhost:3000/admin_
, you are redirected to_localhost:3000/login to_
require login
localhost:3000/admin
— https://www.davidroyer.me/blog/nuxtjs-firebase-auth/
— https://github.com/wahengchang/nuxt-firebase-starter-kit/pulls?q=is%3Apr+is%3Aclosed
— https://codeburst.io/nuxt-authentication-from-scratch-a7a024c7201b