Nuxt middleware not triggered upon initial render - firebase

The following code is meant to check the role of the user.
The middleware runs everytime the site is reloaded are a new route is taken.
// Some nuxt middleware
import * as firebase from 'firebase/app'
import 'firebase/auth'
export default function ({ app, store, route, redirect }) {
app.router.beforeEach((to, from, next) => {
// For some reason, this does not load every time.
firebase.auth().onAuthStateChanged((userAuth) => {
if (userAuth) {
console.log(userAuth)
firebase
.auth()
.currentUser.getIdTokenResult()
.then(function ({ claims }) {
// some auth stuff
})
})
}
For some reason, if the site is reloaded this user auth function always returns null. This leads to that the rest of the functions fail due to the unknown user data / user roles.
firebase.auth().onAuthStateChanged((userAuth) => {...})
So my question is, why does the upper function return null when the site is reloaded?
ps. Everything works normal if a new route is taken, it only fails when site is reloaded.

beforeEach is a guard triggered when you navigate from a page to another page thanks to vue router, aka using <nuxt-link> or $router.push.
On the initial page load, there is no navigation because you're rendering the content generated by the server, not the client directly.
Definition of a middleware from Nuxt's documentation
Middleware lets you define custom functions that can be run before rendering either a page or a group of pages (layout).
Notice, before rendering. This means that a middleware will be run as your beforeEach and on initial render.
Hence, you can totally strip the router guard part and simply let the middleware as this
export default function ({ app, store, route, redirect }) {
firebase.auth().onAuthStateChanged((userAuth) => {
...

Related

Vercel circular redirects when using Firebase authentication

I do have a super weird error coming up only when deploying the code to Vercel. It doesn't happen locally which makes it quite annoying to begin with.
I do have a staging and a production instance for my code. I want to protect the staging with a password which is not difficult since I implemented the authentication via Firebase. The only tricky part is that I don't use Firebase to keep track of the user but my server (basically setting a cookie). I should mention that I am using Sveltekit to put it all together.
In sveltekit you can use hooks, which can be seen as middlewares, to redirect a user to the sign-in page if the env variable for the environment is set to dev.
Another hook redirects a logged-in user, so if you are already logged in and try to go to auth/sign-in or auth/sign-up you'll get redirected to the home page.
Now the weird happens: I go on the deployed version of the site, and I get immediately redirected to the sign-in page, which is correct. I try to navigate to all the pages of the website, the redirect still works fine. I log in and upon success, I should be redirected to the homepage, which I do BUT the home page redirects me to the sign-in page as if I wasn't logged in and again the sign-in page redirects me to the home page as if I was, thus creating a loop.
I honestly don't know why this happens since it perfectly works locally, so my thoughts go to Vercel. I would exclude Firebase since I remembered to put the custom domain as an allowed domain in the settings.
To give a bitmore context, I structured the hooks responsible for the redirect in this way:
export const authSessionHandler: Handle = async ({ event, resolve }) => {
const cookie = event.locals.cookie;
const idToken = await getIdTokenFromSessionCookie(getCookieValue(cookie, 'session'));
const user = idToken
? {
uid: idToken?.sub,
email: idToken?.email
}
: null;
event.locals.idToken = idToken;
event.locals.user = user;
return resolve(event);
};
export const redirectLoggedInUserHandler: Handle = async ({ event, resolve }) => {
const { user } = event.locals;
const next = event.url.searchParams.get('next') || '/';
if (
user &&
(event.url.pathname.startsWith('/auth/sign-in') ||
event.url.pathname.startsWith('/auth/sign-up'))
) {
return new Response('Redirect', {
status: http_302.status,
headers: {
location: `${next}`
}
});
}
return resolve(event);
};
export const redirectToSignInForDevEnvironmentHandler: Handle = async ({ event, resolve }) => {
const { user } = event.locals;
const allowedEndpoints = ['/auth/sign-in', '/auth/session'];
if (!user && env === 'dev' && !allowedEndpoints.includes(event.url.pathname)) {
return new Response('Redirect', {
status: http_302.status,
headers: {
location: '/auth/sign-in'
}
});
}
return resolve(event);
};
The handlers are in that order, so the first one populates the user and the rest can check the rest.
In the code I am getting the user from event.locals which kind of decides the entire logic (as it should) and to me it's quite interesting and telling the fact that the sign-in page redirects me to home which mean the user is defined, but the home page redirects back as if the user was not defined. This made me think it is not a problem with the code but probably the provider(s) Vercel or Firebase.
It would be very helpful to know your thoughts about it.

Nuxt 3 can not get the URL hash inside middleware

I am trying to get the hash part from the URL but for some reason at the first load of the page, the middleware will not see the hash.
This is not the case with a reload or when using the navigateTo() method
export default defineNuxtRouteMiddleware(async (to) => {
console.log("Auth -- hash:", to.hash)
})
Got some answers from GitHub, check the conversation:
https://github.com/nuxt/framework/discussions/7505#discussioncomment-3644705
Solution
For getting the hash I just removed the middleware, since is impossible to get the browser hash values on the server. Instead, I changed to using a composable function and calling it from the page that received the URL inside an onMounted() hook.
<script setup lang="ts">
const route = useRoute();
onMounted(() => {
oauthCallback(route.hash) // composable function
})
</script>

nuxtServerInit not receiving cookies [duplicate]

This question already has answers here:
firebase cloud function won't store cookie named other than "__session"
(4 answers)
Closed 10 months ago.
What I am trying to achieve
The basic idea is to send a user to another route when a cookie is received in the Nuxt router middleware.
The middleware is always called both on server-side and client-side, and it works perfectly in the dev environment.
The problem that happens only in production is that the server-side middleware never receives the cookie.
My attempt
The logic is simple: nuxtServerInit is called on the server before the router middleware is called. So it gets the cookie from the user and saves it in Vuex:
nuxtServerInit({ commit }, { req }) {
const token = this.$cookies.get('test');
commit('auth/setToken', { value: !!token}) }
}
Then, the router middleware is called and checks Vuex if the cookie is there to redirect the user:
export default function ({ store, route, redirect }) {
if (route.path === '/' && store.getters['auth/getToken']) { redirect('/test'); }
}
Everything works perfectly fine locally, but upon deployment no redirection happens.What am I missing?
More info
As that may be relevant, I am using a firebase cloud function to host my Nuxt ssr website:
exports.renderApp = functions.https.onRequest(async (req, res) => {
res.set('Cache-Control', 'public, max-age=300, s-maxage=600');
await nuxt.ready(); nuxt.render(req, res);
});
I first thought it may be a cookie problem, but I tried setting them up with vanilla js, then (as implemented above) I tried cookie-universal-nuxt, as well as bypassing Vuex completely and checking the req.headers.cookie directly in the middleware. The result is always the same: works in dev, does not work in production.
Try to change the name of your cookie to __session.
You can find more info in this question.

How to reconcile Firebase Auth token refreshing with Server-Side Rendering

We're using Firebase in a Next.js app at work. I'm new to both, but did my best to read up on both. My problem is more with Firebase, not so much with Next.js. Here's the context:
In the client app, I make some calls to our API, passing a JWT (the ID token) in an Authorization header. The API calls admin.auth().verifyIdToken to check that the ID token is fresh enough. This works fine, since I am more or less guaranteed that the ID token gets refreshed regularly (through the use of onIDTokenChanged (doc link)
Now I want to be able to Server-Side Render my app pages. In order to do that, I store the ID token in a cookie readable by the server. But from here on, I have no guarantee that the ID token will be fresh enough next time the user loads the app through a full page load.
I cannot find a server-side equivalent of onIDTokenChanged.
This blog post mentions a google API endpoint to refresh a token. I could hit it from the server and give it a refresh token, but it feels like I'm stepping out of the Firebase realm completely and I'm worried maintaining an ad-hoc system will be a burden.
So my question is, how do people usually reconcile Firebase auth with SSR? Am I missing something?
Thank you!
I've had that same problem recently, and I solved by handling it myself. I created a very simple page responsible for forcing firebase token refresh, and redirecting user back to the requested page. It's something like this:
On the server-side, check for token exp value after extracting it from cookies (If you're using firebase-admin on that server, it will probably tell you as an error after verifying it)
// Could be a handler like this
const handleTokenCookie = (context) => {
try {
const token = parseTokenFromCookie(context.req.headers.cookie)
await verifyToken(token)
} catch (err) {
if (err.name === 'TokenExpired') {
// If expired, user will be redirected to /refresh page, which will force a client-side
// token refresh, and then redirect user back to the desired page
const encodedPath = encodeURIComponent(context.req.url)
context.res.writeHead(302, {
// Note that encoding avoids URI problems, and `req.url` will also
// keep any query params intact
Location: `/refresh?redirect=${encodedPath}`
})
context.res.end()
} else {
// Other authorization errors...
}
}
}
This handler can be used on the /pages, like this
// /pages/any-page.js
export async function getServerSideProps (context) {
const token = await handleTokenCookie(context)
if (!token) {
// Token is invalid! User is being redirected to /refresh page
return {}
}
// Your code...
}
Now you need to create a simple /refresh page, responsible for forcing firebase token refresh on client-side, and after both token and cookie are updated, it should redirect user back to the desired page.
// /pages/refresh.js
const Refresh = () => {
// This hook is something like https://github.com/vercel/next.js/blob/canary/examples/with-firebase-authentication/utils/auth/useUser.js
const { user } = useUser()
React.useEffect(function forceTokenRefresh () {
// You should also handle the case where currentUser is still being loaded
currentUser
.getIdToken(true) // true will force token refresh
.then(() => {
// Updates user cookie
setUserCookie(currentUser)
// Redirect back to where it was
const decodedPath = window.decodeURIComponent(Router.query.redirect)
Router.replace(decodedPath)
})
.catch(() => {
// If any error happens on refresh, redirect to home
Router.replace('/')
})
}, [currentUser])
return (
// Show a simple loading while refreshing token?
<LoadingComponent />
)
}
export default Refresh
Of course it will delay the user's first request if the token is expired, but it ensures a valid token without forcing user to login again.

Login app with Redux & ReactRouter

I would be thankful if someone could point me into a right direction in understanding the Redux architecture.
I should implement "reducer" functions that will handle my actions.
Reducer functions should be combined and create a store.
Lets say I have a LoginForm (React) component, that makes a XHR request to backend API, and receives a JWT token in response.
When I get the response from the API I should dispatch an action like:
store.dispatch({type: "USER_LOGGED_IN",
payload: {username: "john", JWT: "..."});
This updates the state of my application.
What next?
How do I route to to next page? How do I rerender my components (like navbar, etc.) with the logged in username?
Do I use listeners for that?
Let's say you've a method to authorize user:
import { browserHistory } from 'react-router';
// ...
function promisedApiCall(inputData) {
// ...
// api request to backend with input data
// return a promise
}
/*
* on form submit we call this with input data
*/
function authorizeUser(inputData) {
return promisedApiCall(inputData)
.then((response) => store.dispatch({
type: "USER_LOGGED_IN",
payload: {
username: response.userName,
JWT: response.JWT
}
}))
.then(() => browserHistory.push('/success/path/url'))
.catch(() => browserHistory.push('/failure/path/url'));
}
Assuming you have the following prerequisites:
Created redux store and store object is available in the scope where authorizeUser() is executed.
The method promisedApiCall is the function which makes the request to backend with input data from LoginForm.
promisedApiCall should return a promise. [this is really important]
Configured react-router with redux
Once this is complete, app state is updated with user info and also user will be redirected to a new page. This post explains more about programmatically redirecting using react-router.
Access you app state in you component using Redux connect.
Now you have the user info in your component as props.
react-router has a component browserHistory.You can import that like this,
import {browserHistory} from 'react-router';
And to change your route,
browserHistory.push(<route_where_you want_to_go>);
This will let you change the route.

Resources