Fantastic intro to Nuxt and firebase Auth. I feel like a now have a good handle on this. Just a few notes: There are a few methods on `h3` that have been removed on the latest versions so the API functions need to be changed to use `defineEventHandler` and the req/res pulled from the `event.node` and the user added to the `event.context` instead. Also as other people have said, this isn't secure (apart from having API keys in the frontend code, so just worth making sure this is for your own demos and not production code 😎 That said, the point is to upskill you in the tech itself, and for that this video is excellent - in-depth and broad enough to make it well worth the 2 1/2 hours (+ coding time) of watching. Thanks
Check out our Nuxt3/Firestore series. Part 1 - ruclips.net/video/NH8OGNufgAQ/видео.html Part 2 - ruclips.net/video/eylH4KxDJJw/видео.html. Keep an eye out for more parts coming soon!
This is great. Not only learning how to pop firebase into next but also learned how to use middleware, plugins and routes along the way. Very useful indeed.
Check out our Nuxt3/Firestore series. Part 1 - ruclips.net/video/NH8OGNufgAQ/видео.html Part 2 - ruclips.net/video/eylH4KxDJJw/видео.html. Keep an eye out for more parts coming soon!
At 1:58:16 does anyone else have a problem importing the useCookie function? I get the error: "'"h3"' has no exported member named 'useCookie'". I can't find the part of the documentation he was referencing on the website at that point; I'm not sure what has changed since then.
I was able to get it to work with server/middleware/authUser.ts: export default defineEventHandler((event) => { const cookies = parseCookies(event); const authUser = cookies.authUserCookie; event.context.authUser = authUser; }) and server/me.ts: export default defineEventHandler((event) => { return event.context.authUser; })
Given we are using cookie tokens: According to Firebase documentation after version 4.0 the "onAuthStateChanged" observer only triggers on "sign in" and "sign out" events no more on "token expiry". The observer "onIdTokenChanged" does trigger with sign-in, sign-out, and token refresh events. Hope it helps! Amazing tutorial!
This video was helpful in getting me started, but it should be pointed out that server side auth check that's done here is not secure. In both methods shown (sending the cookie or a fetch request) you'd be trusting whatever the client sends. This would make it easy for a user to make the server think they're logged in when they're not or impersonate another user
I have an issue with $auth being undefined at point 1:17:50, which I think you are experiencing too. (I think, ) If you look at it, you are signed in but cannot access the /secret page. I logged out the $auth in authMiddleware, it says undefined. The lifecycle of the app hits the middleware first before initializing the firebase. I'm currently experiencing this issue, do you have any solution for it?
Hi, Not the "correct" solution but I got it working by checking for a cookie instead of waiting for the firebase initialization. When the user creates and account or signs in, I set a cookie in the method with the value of the firebase user information: const response = await signInUser(email, password); const userCookie = useCookie("userCookie"); userCookie.value = response; Then in the plugins/auth.ts, I check for the cookie instead of the auth.currentUser: addRouteMiddleware('auth', () => { const userCookie = useCookie("userCookie"); if (!userCookie?.value?.user) { return navigateTo('/login') } }) When the user signs out, I just set the cookie value to empty in the signOut method: const userCookie = useCookie("userCookie"); userCookie.value = null; I also do the same but to redirect a signed in user away from the sign-in page: addRouteMiddleware('signedIn', () => { const userCookie = useCookie("userCookie"); if (userCookie?.value?.user) { return navigateTo('/') } }) Tried hundreds of things and this was the only thing that gives me what I want :)
can some one explain a little bit deeper the problem and solution Corey had at 32:42, in having to use the onMounted hook due to the plugin being on the client side. I thought setup would pick this up, as I guess he did by trying that first
Thanks so much! this really helped get us started in our transition to Nuxt 3!! Quick question... can the query be tweaked to return one specific document in the collection if we pass the doc ID?
Thanks for your esay tutorial. I tried this works good but when we signed in the secret page is visible when i refresh this page it navigate to index page eventhough i signed in, why can we fix it?
nuxt.config.ts runtimeConfig: { // Private keys are only available on the server apiSecret: '123456789', // Public keys that are exposed to the client public: { apiBase: process.env.FIREBASE_API_KEY || '/api' } }, firebaseAuth.client.ts const config = useRuntimeConfig() const firebaseConfig = { apiKey: config.public.apiBase, };
Great video thanks! Btw to get fast refresh working properly on Windows, create a file called vite.config.js and add the following: export default defineConfig({ server: { watch: { usePolling: true, }, }, })
so far so good but my terminal is spewing out loads of garbage. all seems to be ok but my OCD hates it, any ideas? it obv firebase related, here is the first 40 of about 100 lines: FirebaseAppImpl { 20:27:53 _isDeleted: false, _options: { apiKey: 'AIzaSyCI0hBgq7dEvCNmIiUVjh7bGd8Vi79dJUk' }, _config: { name: '[DEFAULT]', automaticDataCollectionEnabled: false }, _name: '[DEFAULT]', _automaticDataCollectionEnabled: false, _container: ComponentContainer { name: '[DEFAULT]',
Great video! I followed through the tutorial and my secret page is working, but if I navigate to "(website URL)/secret" or use "location.href("/secret") in another function after the user has been authenticated, I am redirected to the home page. Is the middleware supposed to treat "NuxtLink"s and direct links differently in this scenario? I am trying to create a function that both signs in the user and navigates to the secret page without using the NuxtLink feature. Thanks!
Its because your firebaseUser state is empty on page initialize. It will take time to get the user from onAuthStateChange (initUser), but your middleware read it before initUser run. To work around it is to *persist* firebaseUser data, you can save it to localStorage after fetching it on userInit, then change firebaseUser initial data to get the *persist* data from localStorage.
Fantastic intro to Nuxt and firebase Auth. I feel like a now have a good handle on this. Just a few notes: There are a few methods on `h3` that have been removed on the latest versions so the API functions need to be changed to use `defineEventHandler` and the req/res pulled from the `event.node` and the user added to the `event.context` instead. Also as other people have said, this isn't secure (apart from having API keys in the frontend code, so just worth making sure this is for your own demos and not production code 😎 That said, the point is to upskill you in the tech itself, and for that this video is excellent - in-depth and broad enough to make it well worth the 2 1/2 hours (+ coding time) of watching. Thanks
This is extremely helpful. I like the way you go through the documentation and explain everything.
Thorough implementation of Firebase auth showcasing Nuxt 3 features. Great job! Hopefully, there are more Nuxt 3 videos to come!
Check out our Nuxt3/Firestore series. Part 1 - ruclips.net/video/NH8OGNufgAQ/видео.html Part 2 - ruclips.net/video/eylH4KxDJJw/видео.html. Keep an eye out for more parts coming soon!
This is great. Not only learning how to pop firebase into next but also learned how to use middleware, plugins and routes along the way. Very useful indeed.
This is an excellent tutorial. Kudos and thank you!
HI Donnie. Very happy to hear you found this useful!
T5 .t8
M I ij0
Compeletly enough for starting to use firebase in Nuxtjs 3. I hope to see more videos such this
Wow you save my days sir. thank you so much for this great video. thank you for sharing it. God bless you.
You are very welcome
Thank you 😊😊way better way than what I was doing. Subbed
Great video! Would love to see an add-on video with firestore composables.
Check out our Nuxt3/Firestore series. Part 1 - ruclips.net/video/NH8OGNufgAQ/видео.html Part 2 - ruclips.net/video/eylH4KxDJJw/видео.html. Keep an eye out for more parts coming soon!
At 1:58:16 does anyone else have a problem importing the useCookie function? I get the error: "'"h3"' has no exported member named 'useCookie'". I can't find the part of the documentation he was referencing on the website at that point; I'm not sure what has changed since then.
I was able to get it to work with server/middleware/authUser.ts: export default defineEventHandler((event) => {
const cookies = parseCookies(event);
const authUser = cookies.authUserCookie;
event.context.authUser = authUser;
}) and server/me.ts: export default defineEventHandler((event) => {
return event.context.authUser;
})
Thanks, best video!!!
...and im spent. well done!
Given we are using cookie tokens: According to Firebase documentation after version 4.0 the "onAuthStateChanged" observer only triggers on "sign in" and "sign out" events no more on "token expiry". The observer "onIdTokenChanged" does trigger with sign-in, sign-out, and token refresh events.
Hope it helps! Amazing tutorial!
Thanks for the tip! We are planning an updated tutorial now that Nuxt 3 is production ready.
Any ideas on removing the flicker on load?
This video was helpful in getting me started, but it should be pointed out that server side auth check that's done here is not secure. In both methods shown (sending the cookie or a fetch request) you'd be trusting whatever the client sends. This would make it easy for a user to make the server think they're logged in when they're not or impersonate another user
I'm new to nuxt and haven't tried this, but what I imagine you might do is save the firebase JWT in a cookie and validate it on the server
Correct, this should be handled through the firebase admin sdk in order to be secure.
I'm having serious problems (errors) with the nuxt.config.ts file at around 13:35... sadness
I have an issue with $auth being undefined at point 1:17:50, which I think you are experiencing too. (I think, )
If you look at it, you are signed in but cannot access the /secret page. I logged out the $auth in authMiddleware, it says undefined.
The lifecycle of the app hits the middleware first before initializing the firebase.
I'm currently experiencing this issue, do you have any solution for it?
Hi , have you any solution for this? , I have de same situation
Same issue here :(
same issue here! any help?
HI All. No solution yet and we have not circled back to find out the root cause or not. Please let us know if you find a solution before we do.
Hi,
Not the "correct" solution but I got it working by checking for a cookie instead of waiting for the firebase initialization.
When the user creates and account or signs in, I set a cookie in the method with the value of the firebase user information:
const response = await signInUser(email, password);
const userCookie = useCookie("userCookie");
userCookie.value = response;
Then in the plugins/auth.ts, I check for the cookie instead of the auth.currentUser:
addRouteMiddleware('auth', () => {
const userCookie = useCookie("userCookie");
if (!userCookie?.value?.user) {
return navigateTo('/login')
}
})
When the user signs out, I just set the cookie value to empty in the signOut method:
const userCookie = useCookie("userCookie");
userCookie.value = null;
I also do the same but to redirect a signed in user away from the sign-in page:
addRouteMiddleware('signedIn', () => {
const userCookie = useCookie("userCookie");
if (userCookie?.value?.user) {
return navigateTo('/')
}
})
Tried hundreds of things and this was the only thing that gives me what I want :)
Great tutorial! Muchas gracias
can some one explain a little bit deeper the problem and solution Corey had at 32:42, in having to use the onMounted hook due to the plugin being on the client side. I thought setup would pick this up, as I guess he did by trying that first
Thanks so much! this really helped get us started in our transition to Nuxt 3!! Quick question... can the query be tweaked to return one specific document in the collection if we pass the doc ID?
Awesome tutorial, I failed at the cookie part, h3 wasn't liking useCookie. But the standard auth was super thanks
Glad it helped!
Thanks for your esay tutorial. I tried this works good but when we signed in the secret page is visible when i refresh this page it navigate to index page eventhough i signed in, why can we fix it?
Just added an issue on the github repo. When I write /secret right away from the url box the middleware will not work as expected.
can you please show firebase phone authentication in Nuxt js, i was stuck when creating app verifier in phone auth
Why do you use Netlify when Firebase already provides hosting?
Because I prefer Netlify and use it for all my other tutorials. I prefer the almost "non setup" workflow of Netlify and its overall easy of use.
but keep in mind that firebase hosting doenst support SSR by itself. U need to enable the billing and use cloud functions.
Any idea how to import .evn variable to a plugin in 12.2022?
nuxt.config.ts
runtimeConfig: {
// Private keys are only available on the server
apiSecret: '123456789',
// Public keys that are exposed to the client
public: {
apiBase: process.env.FIREBASE_API_KEY || '/api'
}
},
firebaseAuth.client.ts
const config = useRuntimeConfig()
const firebaseConfig = {
apiKey: config.public.apiBase,
};
Great video thanks! Btw to get fast refresh working properly on Windows, create a file called vite.config.js and add the following:
export default defineConfig({
server: {
watch: {
usePolling: true,
},
},
})
folder structure is complicated for me.
so far so good but my terminal is spewing out loads of garbage. all seems to be ok but my OCD hates it, any ideas? it obv firebase related, here is the first 40 of about 100 lines: FirebaseAppImpl { 20:27:53
_isDeleted: false,
_options: { apiKey: 'AIzaSyCI0hBgq7dEvCNmIiUVjh7bGd8Vi79dJUk' },
_config: { name: '[DEFAULT]', automaticDataCollectionEnabled: false },
_name: '[DEFAULT]',
_automaticDataCollectionEnabled: false,
_container: ComponentContainer {
name: '[DEFAULT]',
fixed by changing file name to include client
Great video! I followed through the tutorial and my secret page is working, but if I navigate to "(website URL)/secret" or use "location.href("/secret") in another function after the user has been authenticated, I am redirected to the home page. Is the middleware supposed to treat "NuxtLink"s and direct links differently in this scenario? I am trying to create a function that both signs in the user and navigates to the secret page without using the NuxtLink feature. Thanks!
Its because your firebaseUser state is empty on page initialize.
It will take time to get the user from onAuthStateChange (initUser), but your middleware read it before initUser run.
To work around it is to *persist* firebaseUser data, you can save it to localStorage after fetching it on userInit, then change firebaseUser initial data to get the *persist* data from localStorage.