[Vuejs]-Nuxt 3 + msal โ€“ non_browser_environment error

1๐Ÿ‘

โœ…

You need to make sure that you try to login only in the browser because Nuxt runs also server side.

You can check if you are client side with process.client or process.server for server side.

<script setup>
if (process.client) {
const auth = useAuth();
auth.signIn() // Try to sign in but only on client.
}
</script>

NuxtJS/VueJS: How to know if page was rendered on client-side only?

๐Ÿ‘คPierre Said

0๐Ÿ‘

I found auth module for Nuxt 3. Maybe it can help you

import { NuxtAuthHandler } from '#auth';
import AzureADProvider from 'next-auth/providers/azure-ad';
async function refreshAccessToken(accessToken) {
    try {
        const url = `https://login.microsoftonline.com/${process.env.AZURE_AD_TENANT_ID}/oauth2/v2.0/token`;
        const req = await fetch(url, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body:
                `grant_type=refresh_token` +
                `&client_secret=${process.env.AZURE_AD_CLIENT_SECRET}` +
                `&refresh_token=${accessToken.refreshToken}` +
                `&client_id=${process.env.AZURE_AD_CLIENT_ID}`,
        });
        const res = await req.json();
        return {
            ...accessToken,
            accessToken: res.access_token,
            accessTokenExpires: Date.now() + res.expires_in * 1000,
            refreshToken: res.refresh_token ?? accessToken.refreshToken, // Fall back to old refresh token
        };
    } catch (error) {
        console.log(error);
        return {
            ...accessToken,
            error: 'RefreshAccessTokenError',
        };
    }
}
export default NuxtAuthHandler({
    secret: process.env.NUXT_AUTH_SECRET,
    providers: [
        AzureADProvider.default({
            clientId: process.env.AZURE_AD_CLIENT_ID,
            clientSecret: process.env.AZURE_AD_CLIENT_SECRET,
            tenantId: process.env.AZURE_AD_TENANT_ID,
            authorization: {
                params: {
                    scope: `offline_access openid profile email ${process.env.AZURE_AD_CLIENT_ID}/access_as_user`,
                },
            },
        }),
    ],
    callbacks: {
        async jwt({ token, account, profile }) {
            // Persist the access_token in the encrypted JWT.
            if (account && profile) {
                token.accessToken = account.access_token;
                token.accessTokenExpires = account.expires_at * 1000;
                token.refreshToken = account.refresh_token;
            }
            if (Date.now() < token.accessTokenExpires) {
                return token;
            }
            return refreshAccessToken(token);
        },
    },
});

Docs โ€“ https://sidebase.io/nuxt-auth/recipes/azure-ad-example

๐Ÿ‘คVitaliy

Leave a comment