<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Eugene Moskalenko on Medium]]></title>
        <description><![CDATA[Stories by Eugene Moskalenko on Medium]]></description>
        <link>https://medium.com/@testjokerqwerty?source=rss-f904f2e9f03f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*WIOvtiqDw9uppbeFW8COLQ.jpeg</url>
            <title>Stories by Eugene Moskalenko on Medium</title>
            <link>https://medium.com/@testjokerqwerty?source=rss-f904f2e9f03f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 02:21:46 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@testjokerqwerty/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Google One Tap Auth in Nuxt 4: The Minimalist Guide]]></title>
            <link>https://medium.com/@testjokerqwerty/google-one-tap-auth-in-nuxt-4-the-minimalist-guide-b86dd2ba1fd2?source=rss-f904f2e9f03f------2</link>
            <guid isPermaLink="false">https://medium.com/p/b86dd2ba1fd2</guid>
            <category><![CDATA[onetap]]></category>
            <category><![CDATA[google-one-tap]]></category>
            <category><![CDATA[vuejs]]></category>
            <category><![CDATA[nuxtjs]]></category>
            <category><![CDATA[vue]]></category>
            <dc:creator><![CDATA[Eugene Moskalenko]]></dc:creator>
            <pubDate>Sun, 12 Apr 2026 16:04:49 GMT</pubDate>
            <atom:updated>2026-04-12T16:04:49.889Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oK3Wg3gpG4u7AKTypDPPQw.jpeg" /></figure><h3>Streamline your user experience by adding one-click authentication to your Nuxt 4 application.</h3><p>In my <a href="https://medium.com/@testjokerqwerty/authentication-in-nuxt-4-without-third-party-modules-a-complete-guide-677999744ecf">previous article</a>, we built a robust authentication system from scratch without relying on heavy third-party modules. Today, we are taking it a step further by integrating <strong>Google One Tap</strong>.</p><p>This feature allows returning users to sign in with a single tap, removing the friction of traditional login forms.</p><h3>1. Installation</h3><p>First, we need a lightweight wrapper for the Google Identity Services SDK. We’ll use vue3-google-signin.</p><p>Bash</p><pre>npm install vue3-google-signin@^2.1.1</pre><h3>2. Get Your Google Client ID</h3><p>To interact with Google APIs, you need credentials.</p><ul><li>Go to the <a href="https://console.cloud.google.com/apis/credentials">Google Cloud Console</a>.</li><li>Create an <strong>OAuth 2.0 Client ID</strong>.</li><li>Add your domain (and localhost) to the <strong>Authorized JavaScript origins</strong>.</li></ul><h3>3. Configuration</h3><p>Add your Client ID to your .env file:</p><p>Фрагмент коду</p><pre>NUXT_PUBLIC_GOOGLE_CLIENT_ID=&quot;your-client-id.apps.googleusercontent.com&quot;</pre><p>Then, expose it via nuxt.config.ts. This makes the key accessible on the client side through Nuxt&#39;s runtimeConfig.</p><p>TypeScript</p><pre>export default defineNuxtConfig({<br>  runtimeConfig: {<br>    public: {<br>      // ... your other config<br>      NUXT_PUBLIC_GOOGLE_CLIENT_ID: process.env.NUXT_PUBLIC_GOOGLE_CLIENT_ID,<br>    },<br>  },<br>})</pre><h3>4. Create the Plugin</h3><p>We need to initialize the library globally. Create a new file plugins/google-signin.client.ts. Using the .client suffix ensures this only runs in the browser.</p><p>TypeScript</p><pre>import GoogleSignInPlugin from &#39;vue3-google-signin&#39;</pre><pre>export default defineNuxtPlugin((nuxtApp) =&gt; {<br>    const env = useRuntimeConfig()</pre><pre>    nuxtApp.vueApp.use(GoogleSignInPlugin, {<br>        clientId: env.public.NUXT_PUBLIC_GOOGLE_CLIENT_ID,<br>    })<br>})</pre><h3>5. Implement One Tap in Your Layout</h3><p>The best place for One Tap is usually in your main layout (e.g., default.vue). It will automatically prompt the user if they aren&#39;t logged in.</p><p>TypeScript</p><pre>import { type CredentialResponse, useOneTap } from &#39;vue3-google-signin&#39;</pre><pre>const api = useApi()<br>const authStore = useAuthStore()<br>const { isAuthenticated } = storeToRefs(authStore)<br>const { setTokens, fetchUser } = authStore</pre><pre>// Initialize Google One Tap<br>useOneTap({<br>    // Disable the prompt if the user is already authenticated<br>    disableAutomaticPrompt: isAuthenticated.value,<br>    onSuccess: async (response) =&gt; {<br>        try {<br>            // Send the credential to your backend<br>            const res = await api.singOneTap(response as CredentialResponse)<br>            setTokens(res.access_token, res.refresh_token)<br>            await fetchUser()<br>        } catch (err) {<br>            console.error(&#39;Backend sync failed:&#39;, err)<br>        }<br>    },<br>    onError: () =&gt; console.error(&#39;Error with One Tap Login&#39;),<br>})</pre><h3>6. Update the Auth Store</h3><p>Finally, ensure your authStore has the necessary methods to handle the new tokens and user data:</p><p>TypeScript</p><pre>const setUser = (data: User) =&gt; {<br>    user.value = data<br>}</pre><pre>const setTokens = (access_token: string | null, refresh_token: string | null) =&gt; {<br>    accessToken.value = access_token<br>    refreshToken.value = refresh_token<br>}</pre><h3>Result</h3><p>Now, when a user visits your site and they are not logged in, a sleek Google One Tap dialog will appear in the top-right corner. One click, and they are authenticated!</p><p>You can find the full source code for this implementation on GitHub: 👉 <a href="https://github.com/yevheniimoskalenko/nuxt4-auth"><strong>nuxt4-auth repository</strong></a></p><h3>Support the Journey</h3><p>If you found this guide helpful, <strong>please follow me here on Medium</strong>. Your support and claps let me know that these technical deep-dives are useful to the community and motivate me to share more Nuxt 4 insights! 🚀</p><p><strong>Tags:</strong> <em>Nuxt.js, Vue.js, Google One Tap, Authentication, Web Development, JavaScript</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b86dd2ba1fd2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Authentication in Nuxt 4 Without Third-Party Modules: A Complete Guide]]></title>
            <link>https://medium.com/@testjokerqwerty/authentication-in-nuxt-4-without-third-party-modules-a-complete-guide-677999744ecf?source=rss-f904f2e9f03f------2</link>
            <guid isPermaLink="false">https://medium.com/p/677999744ecf</guid>
            <category><![CDATA[pinia]]></category>
            <category><![CDATA[auth]]></category>
            <category><![CDATA[jwt]]></category>
            <category><![CDATA[nuxt-4]]></category>
            <category><![CDATA[nuxtauth]]></category>
            <dc:creator><![CDATA[Eugene Moskalenko]]></dc:creator>
            <pubDate>Thu, 19 Feb 2026 13:19:33 GMT</pubDate>
            <atom:updated>2026-02-19T13:19:33.126Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="nuxt 4 auth without module" src="https://cdn-images-1.medium.com/max/1024/1*VEzMeX-kVeQ-wjk0d8PvkA.png" /></figure><p><strong>Building a production-ready JWT auth system from scratch using only Pinia, useCookie, and ofetch.</strong></p><p>Every time I start a new Nuxt project and reach the authentication step, I see the same suggestion: “just install @sidebase/nuxt-auth&quot; or &quot;use nuxt-auth-utils.&quot; And while these modules are great, they often come with trade-offs — opinionated configurations, limited flexibility, or bloated abstractions that don&#39;t match your backend&#39;s token flow.</p><p>So I asked myself: <strong>what if we build it from scratch?</strong></p><p>Turns out, Nuxt 4 already ships with everything you need — useCookie for SSR-safe token storage, ofetch for HTTP with interceptors, and Pinia for state management. No extra dependencies. No black boxes.</p><p>In this article, I’ll walk you through a complete, production-ready authentication system that handles:</p><ul><li>✅ JWT access + refresh token flow</li><li>✅ SSR-compatible token storage via cookies</li><li>✅ Automatic token refresh on 401 responses</li><li>✅ Auth, Guest, and Role-based route middleware</li><li>✅ App-level auth initialization plugin</li><li>✅ Fully typed with TypeScript</li></ul><p>Let’s get started.</p><h3>Project Structure</h3><p>Here’s the architecture we’ll build:</p><pre>app/<br>├── composables/<br>│   └── useApi.ts<br>├── middleware/<br>│   ├── auth.ts                # Protect authenticated routes<br>│   ├── guest.ts               # Prevent logged-in users from login page<br>│   └── role.ts                # Role-based access control<br>├── plugins/<br>│   ├── api.ts                 # ofetch instance with interceptors<br>│   └── auth-init.ts           # Auto-check auth on app start│   └── auth-init.ts           # Auto-check auth on app start<br>├── shared/<br>│   ├── types<br>│   │   └── auth.types.ts      # TypeScript interfaces<br>│   └── utils/<br>│       └── jwt.utils.ts       # Client-side JWT decode helpers<br>├── stores/<br>│   └── useAuthStore.ts        # Pinia auth store<br>└── pages/<br>├── index.vue              # Login page<br>└── dashboard/<br>└── index.vue          # Protected page</pre><p>Clean. Modular. No magic.</p><h3>Step 1: Define Your Types</h3><p>Start with solid TypeScript contracts. This ensures type safety across the entire auth flow.</p><pre>// shared/types/auth.types.ts<br><br>Why types first? When your auth flow has a single source of truth for shapes, every layer - store, API, middleware - stays in sync. If your backend changes a response format, TypeScript catches it immediately.<br>export interface UserRole {<br>    id: number<br>    value: string<br>    description: string<br>}<br><br>export interface User {<br>    id: number<br>    email: string<br>    firstName: string<br>    lastName: string<br>    phone?: string<br>    picture?: string<br>    verified: boolean<br>    banned: boolean<br>    banReason?: string<br>    roles: UserRole[]<br>    bonusWallet: number<br>    wallet: number<br>    createdAt: string<br>    updatedAt: string<br>    tariff?: {<br>        id: number<br>        name: string<br>    }<br>}<br><br>export interface AuthTokens {<br>    access_token: string<br>    refresh_token: string<br>}<br><br>export interface LoginRequest {<br>    email: string<br>    password: string<br>}<br><br>export interface LoginResponse {<br>    data: {<br>        tokens: AuthTokens<br>    }<br>}<br><br>export interface RefreshRequest {<br>    token: string<br>}<br><br>export interface RefreshResponse {<br>    data: {<br>        tokens: AuthTokens<br>    }<br>}<br><br>export interface VerifyEmailRequest {<br>    email: string<br>    code: string<br>}<br><br>export interface CreateAuthRequest {<br>    email: string<br>    password: string<br>    firstName: string<br>    lastName: string<br>    role: &#39;OWNER&#39; | &#39;PLAYER&#39;<br>    phoneNumber: string<br>    ref?: number<br>}<br><br>export interface GoogleAuthRequest {<br>    access_token: string<br>    authuser: string<br>    expires_in: number<br>    scope: string<br>    token_type: string<br>}<br><br>export interface GoogleOneTapRequest {<br>    credential: string<br>    select_by: string<br>}<br><br>export interface CreateGoogleUserRequest {<br>    role: string<br>    tariff: number<br>    googleData: GoogleAuthRequest<br>}<br><br>export interface JwtPayload {<br>    id: number<br>    email: string<br>    roles: UserRole[]<br>    iat: number<br>    exp: number<br>}</pre><h3>Step 2: Create the API Plugin with Interceptors</h3><p>This is the <strong>heart</strong> of the system. We create a custom ofetch instance that:</p><ol><li>Automatically attaches the Authorization header.</li><li>Intercepts 401 responses and silently refreshes the token.</li><li>Retries the original request with the new token.</li><li>Logs the user out if refresh fails.</li></ol><pre>// plugins/api.ts<br>// plugins/api.ts<br>import { ofetch } from &#39;ofetch&#39;<br><br>declare module &#39;#app&#39; {<br> interface NuxtApp {<br>  $api: typeof ofetch<br> }<br>}<br><br>declare module &#39;@vue/runtime-core&#39; {<br> interface ComponentCustomProperties {<br>  $api: typeof ofetch<br> }<br>}<br><br>declare global {<br> var $api: typeof ofetch<br>}<br><br>export default defineNuxtPlugin((nuxtApp) =&gt; {<br> const i18nRedirected = useCookie&lt;string&gt;(&#39;i18n_redirected&#39;)<br> const {<br>  public: { BaseURL },<br> } = useRuntimeConfig()<br><br> // Single active refresh promise to avoid race conditions<br> let refreshPromise: Promise&lt;void&gt; | null = null<br> const $api = ofetch.create({<br>  baseURL: BaseURL,<br><br>  async onRequest({ options }) {<br>   const authStore = useAuthStore()<br>   const currentLang = i18nRedirected.value || &#39;uk&#39;<br><br>   // Add Authorization header if we have access token<br>   const headers: Record&lt;string, string&gt; = {<br>    &#39;Accept-Language&#39;: currentLang,<br>   }<br><br>   if (authStore.accessToken) {<br>    headers[&#39;Authorization&#39;] = `Bearer ${authStore.accessToken}`<br>   }<br><br>   options.headers = {<br>    ...options.headers,<br>    ...headers,<br>   } as any<br>  },<br><br>  async onResponseError({ request, options, response }): Promise&lt;any&gt; {<br>   // Handle 401 Unauthorized - token expired<br>   if (response.status === 401 &amp;&amp; !(options as any)._isRetry) {<br>    const authStore = useAuthStore()<br><br>    try {<br>     // Avoid multiple simultaneous refresh calls<br>     if (!refreshPromise) {<br>      refreshPromise = (async () =&gt; {<br>       await authStore.refreshTokens()<br>      })().finally(() =&gt; {<br>       refreshPromise = null<br>      })<br>     }<br><br>     // Wait for token refresh<br>     await refreshPromise<br><br>     // Retry the original request with new token<br>     return await ofetch(request, { ...options, _isRetry: true } as any)<br>    }<br>    catch (e) {<br>     // Refresh failed - logout user<br>     await authStore.logout()<br>     throw e<br>    }<br>   }<br><br>   // Other errors - throw unified error<br>   throw createError({<br>    statusCode: response.status,<br>    statusMessage: response._data?.message || &#39;Unknown error&#39;,<br>   })<br>  },<br> })<br><br> // Make available globally<br> globalThis.$api = $api<br><br> return {<br>  provide: {<br>   api: $api,<br>  },<br> }<br>})</pre><p>The refreshPromise pattern is crucial. Imagine three API calls fire simultaneously, and all three get a 401. Without this guard, you&#39;d trigger three parallel refresh requests — likely invalidating each other. By storing a single promise, all waiting requests share the same refresh cycle.</p><p>The _isRetry flag prevents infinite loops: if the retried request also returns 401, we know the refresh itself failed and log the user out.</p><h3>Step 3: Build the Typed API Composable</h3><p>Wrap your endpoints in a composable for clean, reusable, typed API calls:</p><pre>// composables/useApi.ts<br>import type {<br> LoginRequest,<br> LoginResponse,<br> RefreshRequest,<br> RefreshResponse,<br>} from &#39;~/shared/types/auth.types&#39;<br><br>import type {<br> UserResponse,<br>} from &#39;~/shared/types/user.types&#39;<br><br><br>interface ApiMethods {<br> login: (body: LoginRequest) =&gt; Promise&lt;LoginResponse&gt;<br> refresh: (body: RefreshRequest) =&gt; Promise&lt;RefreshResponse&gt;<br> logout: () =&gt; Promise&lt;void&gt;,<br> fetchMe: () =&gt; Promise&lt;UserResponse&gt;<br><br>}<br><br>export default function (): ApiMethods {<br> return {<br>  fetchMe: async (): Promise&lt;UserResponse&gt; =&gt; await $api&lt;UserResponse&gt;(`/api/users/me`),<br>  login: async (body: LoginRequest): Promise&lt;LoginResponse&gt; =&gt; await $api&lt;LoginResponse&gt;(`/api/auth/sign-in`, {<br>   method: &#39;POST&#39;,<br>   body,<br>  }),<br>  refresh: async (body: RefreshRequest): Promise&lt;RefreshResponse&gt; =&gt; await $api&lt;RefreshResponse&gt;(`/api/auth/refresh`, {<br>   method: &#39;GET&#39;,<br>   query: { token: body.token },<br>  }),<br>  logout: async (): Promise&lt;void&gt; =&gt; await $api(`/api/auth/logout`),<br> }<br>}</pre><blockquote><strong><em>Why a composable instead of calling </em></strong><strong><em>$api directly?</em></strong><em> Centralized endpoint definitions. If a URL changes, you fix it in one place. Plus, TypeScript now knows exactly what each method accepts and returns.</em></blockquote><h3>Step 4: The Auth Store (Pinia)</h3><p>This is where state lives. The store manages:</p><ul><li>Token storage via useCookie (SSR-compatible)</li><li>User data</li><li>Login, logout, refresh, and auth-check flows</li></ul><pre>// stores/useAuthStore.ts<br>/**<br> * Authentication Store<br> * Pinia store for managing authentication state and actions<br> * <br> * Tokens are stored in cookies via useCookie for SSR compatibility<br> */<br><br>import { defineStore } from &#39;pinia&#39;<br>import type { User, LoginRequest, LoginResponse } from &#39;~/shared/types/auth.types&#39;<br><br>export const useAuthStore = defineStore(&#39;auth&#39;, () =&gt; {<br>    // State<br>    const user = ref&lt;User | null&gt;(null)<br><br>    // Cookies for token storage (SSR-compatible)<br>    const accessToken = useCookie&lt;string | null&gt;(&#39;access_token&#39;, {<br>        maxAge: 15 * 60, // 15 minutes<br>        sameSite: &#39;lax&#39;,<br>        secure: process.env.NODE_ENV === &#39;production&#39;,<br>    })<br><br>    const refreshToken = useCookie&lt;string | null&gt;(&#39;refresh_token&#39;, {<br>        maxAge: 30 * 24 * 60 * 60, // 30 days<br>        sameSite: &#39;lax&#39;,<br>        secure: process.env.NODE_ENV === &#39;production&#39;,<br>    })<br><br>    // Getters<br>    const isAuthenticated = computed(() =&gt; !!user.value &amp;&amp; !!accessToken.value)<br><br>    const userRoles = computed(() =&gt; {<br>        return user.value?.roles?.map(r =&gt; r.value) || []<br>    })<br><br>    const hasRole = (role: string | string[]): boolean =&gt; {<br>        const roles = Array.isArray(role) ? role : [role]<br>        return roles.some(r =&gt; userRoles.value.includes(r))<br>    }<br><br>    // Actions<br>    const login = async (credentials: LoginRequest) =&gt; {<br>        const api = useApi()<br><br>        try {<br>            // Backend returns tokens in response body<br>            const response = await api.login&lt;LoginResponse&gt;(credentials)<br><br>            // Store tokens in cookies<br>            accessToken.value = response.data.tokens.access_token<br>            refreshToken.value = response.data.tokens.refresh_token<br><br>            // Fetch user data<br>            await fetchUser()<br><br>            return response<br>        }<br>        catch (error) {<br>            console.error(&#39;Login failed:&#39;, error)<br>            throw error<br>        }<br>    }<br><br>    const logout = async () =&gt; {<br>        const api = useApi()<br><br>        try {<br>            // Call backend logout<br>            await api.logout()<br>        }<br>        catch (error) {<br>            console.error(&#39;Logout API call failed:&#39;, error)<br>        }<br>        finally {<br>            // Clear tokens and user state<br>            accessToken.value = null<br>            refreshToken.value = null<br>            user.value = null<br><br>            // Redirect to login<br>            await navigateTo(&#39;/&#39;)<br>        }<br>    }<br><br>    const refreshTokens = async () =&gt; {<br>        const api = useApi()<br><br>        if (!refreshToken.value) {<br>            throw new Error(&#39;No refresh token available&#39;)<br>        }<br><br>        try {<br>            const response = await api.refresh&lt;LoginResponse&gt;({ token: refreshToken.value })<br><br>            // Update tokens<br>            accessToken.value = response.data.tokens.access_token<br>            refreshToken.value = response.data.tokens.refresh_token<br><br>            return response<br>        }<br>        catch (error) {<br>            console.error(&#39;Token refresh failed:&#39;, error)<br>            // Clear tokens on refresh failure<br>            accessToken.value = null<br>            refreshToken.value = null<br>            throw error<br>        }<br>    }<br><br>    const fetchUser = async () =&gt; {<br>        const api = useApi()<br><br>        try {<br>            const userData = await api.fetchMe&lt;{ data: User }&gt;()<br>            user.value = userData.data<br>            return userData<br>        }<br>        catch (error) {<br>            // Don&#39;t log error here - it may be expected (e.g., expired token)<br>            // Let the caller handle the error<br>            user.value = null<br>            throw error<br>        }<br>    }<br><br>    const checkAuth = async (): Promise&lt;boolean&gt; =&gt; {<br>        // If user already loaded and have token, we&#39;re authenticated<br>        if (user.value &amp;&amp; accessToken.value) {<br>            return true<br>        }<br><br>        // If no tokens at all, not authenticated<br>        if (!accessToken.value &amp;&amp; !refreshToken.value) {<br>            return false<br>        }<br><br>        // If we have refresh_token but no access_token, try to refresh first<br>        if (!accessToken.value &amp;&amp; refreshToken.value) {<br>            try {<br>                await refreshTokens()<br>            }<br>            catch (error) {<br>                // Refresh failed, clear everything<br>                accessToken.value = null<br>                refreshToken.value = null<br>                user.value = null<br>                return false<br>            }<br>        }<br><br>        // Now try to fetch user data<br>        // At this point we should have a valid access_token (fresh or refreshed)<br>        try {<br>            await fetchUser()<br>            return true<br>        }<br>        catch (error: any) {<br>            // If still getting 401, something is wrong - clear tokens<br>            if (error.statusCode === 401) {<br>                accessToken.value = null<br>                refreshToken.value = null<br>                user.value = null<br>            }<br>            return false<br>        }<br>    }<br><br>    return {<br>        // State<br>        user,<br>        accessToken,<br>        refreshToken,<br><br>        // Getters<br>        isAuthenticated,<br>        userRoles,<br>        hasRole,<br><br>        // Actions<br>        login,<br>        logout,<br>        refreshTokens,<br>        fetchUser,<br>        checkAuth,<br>    }<br>})</pre><h3>Key design decisions</h3><p><strong>Why </strong><strong>useCookie instead of </strong><strong>localStorage?</strong> Because localStorage doesn&#39;t exist on the server. With useCookie, tokens are available during SSR — meaning your middleware can check authentication before the page even renders. No flash of unauthorized content.</p><p><strong>Why</strong></p><p><strong>checkAuth has a multi-step flow?</strong> Real-world scenarios are messy. The access token might be expired while the refresh token is still valid. Or both tokens might exist but the user data hasn’t been fetched yet. checkAuth handles every case gracefully.</p><h3>Step 5: Route Middleware</h3><h3>Auth Middleware — Protect private pages</h3><pre>// middleware/auth.ts<br>/**<br> * Authentication Middleware<br> * Protects routes requiring authentication<br> * SSR-compatible - uses Pinia store to check auth status<br> */<br><br>export default defineNuxtRouteMiddleware(async (to, from) =&gt; {<br>    const authStore = useAuthStore()<br>    // Check if user is authenticated<br>    // This will try to fetch user data if not already loaded<br>    const isAuth = await authStore.checkAuth()<br><br>    // Not authenticated - redirect to login<br>    if (!isAuth) {<br>        return navigateTo({<br>            path: &#39;/&#39;,<br>            query: { redirect: to.fullPath },<br>        })<br>    }<br>})</pre><p>Note the redirect query parameter — after login, the user is sent back to where they originally wanted to go.</p><h3>Guest Middleware — Redirect authenticated users away from login</h3><pre>// middleware/guest.ts<br>/**<br> * Guest Middleware<br> * Prevents authenticated users from accessing guest-only pages (e.g., login, register)<br> * Redirects authenticated users to dashboard<br> */<br><br>export default defineNuxtRouteMiddleware(async (to, from) =&gt; {<br>    const authStore = useAuthStore()<br><br>    // Check if user is authenticated<br>    // If user data is already loaded and we have tokens, user is authenticated<br>    if (authStore.isAuthenticated) {<br>        // Prevent authenticated users from accessing guest pages<br>        return navigateTo(&#39;/dashboard&#39;)<br>    }<br><br>    // If we have tokens but no user data yet, wait for auth check<br>    if ((authStore.accessToken || authStore.refreshToken) &amp;&amp; !authStore.user) {<br>        try {<br>            await authStore.checkAuth()<br><br>            // After checking, if authenticated, redirect<br>            if (authStore.isAuthenticated) {<br>                return navigateTo(&#39;/dashboard&#39;)<br>            }<br>        }<br>        catch {<br>            // Auth check failed, allow access to guest page<br>        }<br>    }<br><br>    // User is not authenticated, allow access<br>})</pre><h3>Role Middleware — Fine-grained access control</h3><pre>// middleware/role.ts<br>/**<br> * Role-based Authorization Middleware<br> * Checks if user has required role(s)<br> * SSR-compatible<br> *<br> * Usage in page:<br> * definePageMeta({<br> *   middleware: [&#39;auth&#39;, &#39;role&#39;],<br> *   roles: [&#39;ADMIN&#39;] // or [&#39;ADMIN&#39;, &#39;OWNER&#39;] for multiple roles<br> * })<br> */<br><br>export default defineNuxtRouteMiddleware(async (to, from) =&gt; {<br>    const authStore = useAuthStore()<br><br>    // Ensure user is authenticated first<br>    await authStore.checkAuth()<br><br>    if (!authStore.user) {<br>        return navigateTo({<br>            path: &#39;/&#39;,<br>            query: { redirect: to.fullPath },<br>        })<br>    }<br><br>    // Get required roles from route meta<br>    const requiredRoles = to.meta.roles as string[] | string | undefined<br><br>    if (!requiredRoles) {<br>        console.warn(&#39;Role middleware used but no roles defined in route meta&#39;)<br>        return<br>    }<br><br>    // Check if user has required role<br>    if (!authStore.hasRole(requiredRoles)) {<br>        // Redirect to error page<br>        return navigateTo({<br>            path: &#39;/error&#39;,<br>            query: {<br>                code: &#39;403&#39;,<br>                message: &#39;You do not have permission to access this page&#39;,<br>            },<br>        })<br>    }<br>})</pre><p>Usage in a page component:</p><pre>definePageMeta({<br> layout: &#39;dashboard&#39;,<br> middleware: [&#39;role&#39;],<br> roles: [&#39;ADMIN&#39;, &#39;OWNER&#39;, &#39;PLAYER&#39;],<br>})</pre><p>Combine middleware as needed: middleware: [&#39;auth&#39;, &#39;role&#39;] — auth runs first, role runs second.</p><h3>Step 6: Auth Initialization Plugin</h3><p>This plugin runs once when the app starts (on both server and client) and silently loads the user if tokens exist:</p><pre>// plugins/auth-init.ts<br>/**<br> * Auth Initialization Plugin<br> * Automatically checks auth status and loads user data on app init<br> * Runs on both server and client<br> */<br><br>export default defineNuxtPlugin(async (nuxtApp) =&gt; {<br>    const authStore = useAuthStore()<br><br>    // Only check auth on client-side or during SSR<br>    // Skip on subsequent client-side navigations (handled by middleware)<br>    if (import.meta.server || !nuxtApp.payload.serverRendered) {<br>        // Only attempt to load user if we have tokens<br>        // This prevents unnecessary 401 errors for non-authenticated users<br>        if (authStore.accessToken || authStore.refreshToken) {<br>            try {<br>                await authStore.checkAuth()<br>            }<br>            catch (error) {<br>                // Silent fail - tokens likely expired<br>            }<br>        }<br>    }<br>})</pre><h3>Why this plugin?</h3><p>Without it, the user would see a brief “unauthenticated” state on every page refresh before the middleware kicks in. The plugin pre-loads auth state so the UI is correct from the first render — both during SSR and client-side hydration.</p><p>The import.meta.server || !nuxtApp.payload.serverRendered guard ensures we don&#39;t double-check: if the server already resolved auth, the client skips it. But if the page wasn&#39;t server-rendered (e.g., SPA fallback), the client handles it.</p><h3>Step 7: JWT Utilities (Bonus)</h3><p>Sometimes you need to peek into a token without hitting the server — for example, to show the user’s email in a loading state or check expiry client-side:</p><pre>/**<br> * JWT Token Utilities<br> * Client-side utilities for decoding and validating JWT tokens<br> */<br><br>import type { JwtPayload } from &#39;../types/auth.types&#39;<br><br>/**<br> * Decode JWT token payload (client-side only, no verification)<br> */<br>export function decodeToken(token: string): JwtPayload | null {<br>    try {<br>        const parts = token.split(&#39;.&#39;)<br>        if (parts.length !== 3)<br>            return null<br><br>        const payload = parts[1]<br>        if (!payload)<br>            return null<br><br>        const decoded = atob(payload.replace(/-/g, &#39;+&#39;).replace(/_/g, &#39;/&#39;))<br>        return JSON.parse(decoded)<br>    }<br>    catch {<br>        return null<br>    }<br>}<br><br>/**<br> * Check if JWT token is expired<br> */<br>export function isTokenExpired(token: string): boolean {<br>    const payload = decodeToken(token)<br>    if (!payload || !payload.exp)<br>        return true<br><br>    // Add 10 second buffer to account for clock skew<br>    return Date.now() &gt;= (payload.exp * 1000 - 10000)<br>}<br><br>/**<br> * Get token expiration time in milliseconds<br> */<br>export function getTokenExpiration(token: string): number | null {<br>    const payload = decodeToken(token)<br>    if (!payload || !payload.exp)<br>        return null<br><br>    return payload.exp * 1000<br>}</pre><blockquote><em>⚠️ </em><strong><em>Important:</em></strong><em> This is client-side decoding only — it does </em><strong><em>not</em></strong><em> verify the token’s signature. Never trust decoded data for authorization decisions; that’s the server’s job.</em></blockquote><h3>Minimal Nuxt Config</h3><p>The beauty of this approach — your config stays dead simple:</p><pre>// nuxt.config.ts<br>// https://nuxt.com/docs/api/configuration/nuxt-config<br>const {<br>  BaseURL,<br>} = process.env<br>export default defineNuxtConfig({<br>  compatibilityDate: &#39;2025-07-15&#39;,<br>  devtools: { enabled: true },<br>  runtimeConfig: {<br>    public: {<br>      BaseURL,<br>    },<br>  },<br>  modules: [&#39;@pinia/nuxt&#39;],<br>})</pre><p>One module: @pinia/nuxt. That&#39;s it. No auth modules, no OAuth adapters, no session managers.</p><h3>✅ Use this when you have a custom backend with a JWT access/refresh token flow and want full control over the authentication behavior.</h3><p>✅ <strong>Use this</strong> when you want to understand exactly what’s happening under the hood — no abstractions, no “magic.”</p><p>✅ <strong>Use this</strong> when third-party modules don’t fit your backend’s specific token format, refresh strategy, or role system.</p><p>❌ <strong>Use a module</strong> when you need OAuth/social login out of the box and don’t want to implement the provider flows yourself.</p><h3>Final Thoughts</h3><p>Building authentication from scratch isn’t as scary as it sounds. Nuxt 4 gives you all the primitives: SSR-safe cookies, interceptors, middleware, and plugins. The patterns in this article — centralized token management, automatic refresh, role-based guards — are the same ones used in production applications serving thousands of users.</p><p>The full source code is available on GitHub: <a href="https://github.com/yevheniimoskalenko/nuxt4-auth">https://github.com/yevheniimoskalenko/nuxt4-auth</a></p><p><em>If you found this article useful, </em><strong><em>follow me</em></strong><em> for more practical Nuxt, Vue, and TypeScript guides. I write about real-world patterns — no fluff, just production code. Hit that </em><strong><em>Follow</em></strong><em> button and let’s build better apps together.</em> 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=677999744ecf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering SEO in Nuxt 3/Nuxt 4: How to Build a Universal i18n-Ready Composable]]></title>
            <link>https://medium.com/@testjokerqwerty/mastering-seo-in-nuxt-3-how-to-build-a-universal-i18n-ready-composable-dfde84eb92d6?source=rss-f904f2e9f03f------2</link>
            <guid isPermaLink="false">https://medium.com/p/dfde84eb92d6</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[nuxtjs]]></category>
            <category><![CDATA[i18n]]></category>
            <category><![CDATA[vuejs]]></category>
            <category><![CDATA[seo]]></category>
            <dc:creator><![CDATA[Eugene Moskalenko]]></dc:creator>
            <pubDate>Wed, 04 Feb 2026 07:43:36 GMT</pubDate>
            <atom:updated>2026-02-11T07:51:36.723Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Nuxt 3 SEO composable for automated multi-language meta tags and social sharing." src="https://cdn-images-1.medium.com/max/1024/1*HzZiYGCNu2mSNy0ei4WL2w.png" /></figure><p>If you’ve ever built a multi-language application with Nuxt 3, you know the “SEO boilerplate” struggle. On every single page, you find yourself repeating the same useHead and useSeoMeta blocks, manually mapping translations and worrying about hreflang tags.</p><p>Copy-pasting meta tags isn’t just boring — it’s dangerous. One missed canonical link or a broken og:image can hurt your rankings.</p><p>I decided to solve this by creating a smart, reusable composable: <strong>useSeo</strong>. It automates the boring parts while keeping the flexibility you need for edge cases.</p><h3>The Goal: Write Once, Rank Everywhere</h3><p>The objective was simple:</p><ol><li><strong>Zero Boilerplate</strong>: SEO should work automatically based on the route name.</li><li><strong>Built-in i18n</strong>: Direct integration with @nuxtjs/i18n.</li><li><strong>Technical SEO</strong>: Automated canonical and hreflang generation.</li><li><strong>SSR Friendly</strong>: Seamless support for both useSeoMeta and useServerSeoMeta.</li></ol><h3>The Implementation</h3><p>Here is the logic behind the useSeo composable. It handles translations, environment variables, and reactive meta tags in one place.</p><p>TypeScript</p><pre>// composables/useSeo.ts<br>export default function useSeo({<br>  image = null,<br>  title = null,<br>  robots = null,<br>  description = null,<br>  keywords = null,<br>  author = null,<br>  publisher = null<br>} = {}) {<br>  const localePath = useLocalePath()<br>  const route = useRoute()<br>  const { t, locales, locale } = useI18n()<br>  const env = useRuntimeConfig()<br>  const getRouteBaseName = useRouteBaseName()<br>  <br>  const baseRouteName = computed(() =&gt; getRouteBaseName(route))<br>  const routeName = baseRouteName.value || &#39;error&#39;</pre><pre>  // 1. Clean Canonical URL (removes /uk, /en, etc. from the path)<br>  const canonical = computed(() =&gt; {<br>    const path = route.path.replace(/^\/[a-z]{2}(\/|$)/, &#39;/&#39;)<br>    return env.public.CLIENT_URL + path<br>  })</pre><pre>  // 2. Head Tags (Technical SEO)<br>  useHead({<br>    title: () =&gt; title || t(`seo.${routeName}.meta.title`),<br>    link: [<br>      ...(locales.value.map(({ code, iso }) =&gt; ({<br>        rel: &#39;alternate&#39;,<br>        hreflang: iso,<br>        href: env.public.CLIENT_URL + localePath(routeName, code),<br>      }))),<br>      ...(canonical.value ? [{ rel: &#39;canonical&#39;, href: canonical.value }] : []),<br>    ],<br>    meta: [<br>      ...(keywords ? [{ name: &#39;keywords&#39;, content: keywords }] : []),<br>      ...(author ? [{ name: &#39;author&#39;, content: author }] : []),<br>      ...(publisher ? [{ name: &#39;publisher&#39;, content: publisher }] : [])<br>    ]<br>  })</pre><pre>  // 3. Reactive SEO Meta (Social Media &amp; Client-side)<br>  useSeoMeta({<br>    title: () =&gt; title || t(`seo.${routeName}.meta.title`),<br>    ogTitle: () =&gt; title || t(`seo.${routeName}.meta.title`),<br>    description: () =&gt; description || t(`seo.${routeName}.meta.description`),<br>    ogDescription: () =&gt; description || t(`seo.${routeName}.meta.description`),<br>    ogImage: () =&gt; image || &#39;https://your-default-image-url.jpg&#39;,<br>    ogUrl: env.public.CLIENT_URL + localePath(routeName),<br>    twitterCard: &#39;summary_large_image&#39;,<br>    ogSiteName: &#39;Playfun&#39;,<br>    ogType: &#39;website&#39;,<br>    robots: () =&gt; robots || &#39;index, follow&#39;,<br>    ogLocale: locale.value === &#39;uk&#39; ? &#39;uk-UA&#39; : (locale.value === &#39;fr&#39; ? &#39;fr-FR&#39; : &#39;en_US&#39;)<br>  })</pre><pre>  // 4. Server-Side SEO Meta (Critical for Indexing)<br>  useServerSeoMeta({<br>    title: t(`seo.${routeName}.meta.title`),<br>    ogTitle: t(`seo.${routeName}.meta.title`),<br>    description: description || t(`seo.${routeName}.meta.description`),<br>    ogDescription: description || t(`seo.${routeName}.meta.description`),<br>    ogUrl: env.public.CLIENT_URL + localePath(routeName),<br>    ogType: &#39;website&#39;,<br>    robots: robots || &#39;index, follow&#39;<br>  })</pre><pre>  definePageMeta({<br>    scrollToTop: true<br>  })</pre><pre>  return { baseRouteName: routeName }<br>}</pre><h3>Organizing Your Translations</h3><p>To make this work magically, structure your i18n JSON files to match your route names. For a project like <strong>Playfun</strong>, it looks like this:</p><p>JSON</p><pre>{<br>  &quot;seo&quot;: {<br>    &quot;index&quot;: {<br>      &quot;meta&quot;: {<br>        &quot;title&quot;: &quot;Playfun — Book Sports Venues Online&quot;,<br>        &quot;description&quot;: &quot;Find and book sports venues near you. Fast and easy search for football and tennis.&quot;,<br>        &quot;keywords&quot;: &quot;sports venue booking, football field rental, gym&quot;<br>      }<br>    }<br>  }<br>}</pre><h3>How to Use It</h3><h3>The “Default” Way</h3><p>On most pages, you don’t need to pass any arguments. The composable detects the page name and pulls the right strings from your translation files.</p><p>Фрагмент коду</p><pre>&lt;script setup&gt;<br>// Works automatically!<br>useSeo()<br>&lt;/script&gt;</pre><h3>The “Custom” Way</h3><p>If you are on a dynamic page (like a specific venue or blog post) and need to override the defaults:</p><p>Фрагмент коду</p><pre>&lt;script setup&gt;<br>const { data: venue } = await useFetch(&#39;/api/venue/1&#39;)</pre><pre>useSeo({<br>  title: venue.value.name,<br>  description: venue.value.shortDescription,<br>  image: venue.value.previewImage<br>})<br>&lt;/script&gt;</pre><h3>Conclusion</h3><p>By centralizing SEO logic into a single composable, we’ve achieved:</p><ul><li><strong>Consistency</strong>: Every page now has correct og tags and hreflang alternates.</li><li><strong>Clean Code</strong>: Page components are no longer cluttered with metadata.</li><li><strong>Maintainability</strong>: Changing the logic for all pages happens in one file.</li></ul><p><strong>What’s next?</strong> In my upcoming articles, I’ll show how to extend this composable to include <strong>JSON-LD Structured Data</strong> and dynamic breadcrumbs for even better search visibility.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dfde84eb92d6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Silencing the Noise: Handling Socket.IO Warnings in Nuxt 4]]></title>
            <link>https://medium.com/@testjokerqwerty/silencing-the-noise-handling-socket-io-warnings-in-nuxt-4-75f40db42ba0?source=rss-f904f2e9f03f------2</link>
            <guid isPermaLink="false">https://medium.com/p/75f40db42ba0</guid>
            <category><![CDATA[nuxtjs]]></category>
            <category><![CDATA[socketio]]></category>
            <dc:creator><![CDATA[Eugene Moskalenko]]></dc:creator>
            <pubDate>Tue, 02 Sep 2025 05:10:22 GMT</pubDate>
            <atom:updated>2025-09-05T09:31:25.120Z</atom:updated>
            <content:encoded><![CDATA[<h3>Intro:</h3><p>If you’ve recently upgraded to Nuxt 4 and integrated Socket.IO, you might’ve been greeted by a barrage of Vue Router warnings like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ySl4KohpRg4JLHGZxmDdgw.png" /></figure><pre>[Vue Router warn]: No match found for location with path &quot;/socket.io/?EIO=4&amp;transport=polling&amp;t=2x47t0nq&quot;</pre><p>At first glance, it looks like your frontend is trying to route WebSocket polling requests — which makes no sense. These aren’t user-facing routes, and they shouldn’t be handled by Vue Router at all.</p><p>So what’s going on? And how do we fix it without breaking SSR or middleware logic?</p><h3>🧩 The Problem: Vue Router vs. Socket.IO</h3><p>When using Nuxt 4 with server-side rendering and a custom Socket.IO integration, polling requests like /socket.io/?EIO=4&amp;transport=polling can accidentally hit the frontend routing layer. Since Vue Router doesn’t recognize these paths, it throws warnings — harmless, but noisy and confusing.</p><p>This typically happens when:</p><ul><li>You’re running Nuxt in SSR mode</li><li>Your Socket.IO server is mounted on the same domain</li><li>Polling fallback is enabled (common in production)</li></ul><h3>✅ The Fix: Middleware to the Rescue</h3><p>To silence these warnings and properly handle polling requests, you can create a custom middleware that intercepts /socket.io paths before they reach Vue Router.</p><p>Create a file at server/middleware/socket-ignore.ts:</p><pre>export default defineEventHandler((event) =&gt; {<br>  if (event.req.url?.startsWith(&#39;/socket.io&#39;)) {<br>    event.res.statusCode = 204<br>    event.res.end()<br>  }<br>})</pre><p>This middleware does two things:</p><ul><li>Detects any request starting with /socket.io</li><li>Ends the response early with a 204 No Content status</li></ul><p>This prevents Vue Router from ever seeing the request — no warning, no confusion.</p><h3>🧪 Bonus Tip: Debugging Middleware in Nuxt 4</h3><p>If you’re unsure whether your middleware is being triggered, you can add a quick log:</p><pre>console.log(&#39;Intercepted Socket.IO polling:&#39;, event.req.url)</pre><p>Then restart your dev server and watch the terminal. If you see the log, you’re good to go.</p><h3>🧵 Final Thoughts</h3><p>Nuxt 4’s modular architecture is powerful, but it also means you need to be intentional about what hits your routing layer. Middleware like this gives you fine-grained control — and keeps your logs clean.</p><p>If you’re building real-time apps with Nuxt and Socket.IO, this tiny fix can save hours of debugging and keep your SSR pipeline smooth.</p><p>Want help polishing this into a publish-ready Medium draft with a catchy title, tags, and author bio? I’d be happy to co-write it with you.</p><p>Update:</p><p>I’ve encountered a problem with the port settings. When I change the port to a new one, it works without any warnings or errors. However, the original port seems to be causing issues.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=75f40db42ba0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Integrate nuxt-simple-cookie-consent (GDPR-Compatible) in Nuxt.js]]></title>
            <link>https://medium.com/@testjokerqwerty/how-to-integrate-nuxt-simple-cookie-consent-gdpr-compatible-in-nuxt-js-b1945a9c6ed2?source=rss-f904f2e9f03f------2</link>
            <guid isPermaLink="false">https://medium.com/p/b1945a9c6ed2</guid>
            <category><![CDATA[gdpr]]></category>
            <category><![CDATA[nuxt]]></category>
            <category><![CDATA[gdpr-compatible]]></category>
            <category><![CDATA[nuxt-3]]></category>
            <category><![CDATA[nuxtjs]]></category>
            <dc:creator><![CDATA[Eugene Moskalenko]]></dc:creator>
            <pubDate>Sun, 13 Jul 2025 06:38:50 GMT</pubDate>
            <atom:updated>2025-07-13T06:38:50.127Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to Integrate nuxt-simple-cookie-consent (GDPR-Compatible) in Nuxt.js 3 and Manage Google Analytics with nuxt-gtag</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/582/1*3NZh4ikF1Bj-EuSac_efSw.png" /></figure><p>In this short guide, I will show you step-by-step how to add GDPR-compliant cookie consent to your Nuxt.js 3 project using <a href="https://github.com/pentatrion-software/nuxt-simple-cookie-consent">nuxt-simple-cookie-consent</a>.<br> Additionally, I will explain how to control nuxt-gtag based on the user&#39;s consent preferences.</p><h3>1️⃣ Create a Nuxt 3 Project</h3><p>Before starting, create a fresh Nuxt 3 project if you haven’t already.</p><pre>npx nuxi init my-nuxt-app<br>cd my-nuxt-app<br>npm install</pre><h3>2️⃣ Install Required Dependencies</h3><p>We will install two packages:</p><ul><li><a href="https://github.com/pentatrion-software/nuxt-simple-cookie-consent">nuxt-simple-cookie-consent</a> — for cookie consent management</li><li><a href="https://github.com/nuxt-modules/gtag">nuxt-gtag</a> — to integrate Google Analytics (GA4)</li></ul><pre>npm install nuxt-simple-cookie-consent nuxt-gtag</pre><h3>3️⃣ Configure nuxt.config.ts</h3><p>In your nuxt.config.ts, you need to register both modules:</p><pre>modules: [&#39;nuxt-gtag&#39;, &#39;nuxt-simple-cookie-consent&#39;],</pre><h3>✅ nuxt-simple-cookie-consent Options</h3><p>Below is a sample configuration.<br> This defines how long the user’s choice is stored, the cookie name, version, and how categories are mapped to Google consent mode storage keys:</p><pre>cookieConsent: {<br>	expiresInDays: 180,<br>	consentVersion: &#39;1.0.0&#39;,<br>	cookieName: &#39;cookie_consent&#39;,<br>	gtmConsentMapping: {<br>		analytics: &#39;analytics_storage&#39;,<br>		ads: &#39;ad_storage&#39;,<br>		personalization: &#39;personalization_storage&#39;,<br>	},<br>	categories: {<br>		analytics: {<br>			label: &#39;Analytics&#39;,<br>			description: &#39;Used to improve website performance.&#39;,<br>			required: false,<br>		},<br>		ads: {<br>			label: &#39;Advertisement&#39;,<br>			description: &#39;Used for ad personalization.&#39;,<br>		},<br>	},<br>	scripts: []<br>},</pre><p><strong>Explanation:</strong></p><ul><li>expiresInDays: how long the consent is saved in cookies.</li><li>gtmConsentMapping: this maps categories like analytics or ads to Google&#39;s internal consent keys.</li><li>categories: defines what kind of consent the user can accept or reject.</li></ul><h3>✅ nuxt-gtag Options</h3><pre>gtag: {<br>	initMode: &#39;manual&#39;,<br>	id: GA4, // G-09YRF11M0C<br>	config: {<br>		page_title: &#39;My Custom Page Title&#39;,<br>		anonymize_ip: true,<br>	},<br>},</pre><p><strong>Explanation:</strong></p><ul><li>initMode: &#39;manual&#39;: prevents Google Analytics from initializing automatically.<br> This allows us to respect the user&#39;s consent choice explicitly.</li><li>id: your Google Analytics 4 tracking ID.</li><li>config: additional GA4 config, e.g., anonymizing IPs for GDPR.</li></ul><h3>4️⃣ Displaying the Consent Banner</h3><p>In the next step, you will need to create a simple component (or customize the default one) that shows the user the consent banner.<br> You can easily extend the existing functionality of nuxt-simple-cookie-consent by adding your custom messages, styling, and buttons.</p><h3>5️⃣ Managing Google Analytics Initialization via Plugin</h3><p>Finally, you will need a Nuxt 3 plugin to control when gtag should be initialized based on the user&#39;s consent.</p><p>This is important because with initMode: &#39;manual&#39;, GA won&#39;t run until you explicitly allow it.</p><p>The typical logic in this plugin will look something like:</p><ul><li>Check whether the user accepted analytics.</li><li>If yes — initialize gtag.</li></ul><h3>6️⃣ Create the Cookie Consent Component</h3><p>To display the GDPR cookie banner, you can create a simple reusable component.<br> Below is a typical example that offers two buttons: <strong>Accept All</strong> and <strong>Reject All</strong>.</p><p>Here is the full code of the component:</p><pre>&lt;script setup lang=&quot;ts&quot;&gt;<br>const localePath = useLocalePath()<br>const {<br>  preferences,<br>  acceptAll,<br>  denyAll,<br>  hasUserMadeChoice,<br>  isConsentExpired,<br>  onConsentAccepted,<br>  onConsentDenied,<br>  onCategoryAccepted,<br>  onScriptsInjected,<br>  onScriptsRemoved,<br>  updatePreferences<br>} = useCookieConsent()<br><br>onConsentAccepted(() =&gt; {<br>  console.log(&#39;[HOOK] Consent accepted&#39;)<br>  updatePreferences(preferences.value)<br>})<br><br>onConsentDenied(() =&gt; {<br>  console.log(&#39;[HOOK] Consent denied&#39;)<br>})<br><br>onCategoryAccepted((category) =&gt; {<br>  console.log(&#39;[HOOK] Category accepted:&#39;, category)<br>})<br><br>const showBanner = ref(!hasUserMadeChoice.value || isConsentExpired.value)<br><br>watch([hasUserMadeChoice, isConsentExpired], () =&gt; {<br>  showBanner.value = !hasUserMadeChoice.value || isConsentExpired.value<br>})<br><br>function handleAccept() {<br>  acceptAll()<br>  showBanner.value = false<br>}<br><br>function handleDeny() {<br>  denyAll()<br>  showBanner.value = false<br>}<br>&lt;/script&gt;<br><br>&lt;template&gt;<br>    &lt;div v-if=&quot;showBanner&quot; class=&quot;pointer-events-none fixed inset-x-0 bottom-0 px-6 pb-6 z-20&quot;&gt;<br>        &lt;div class=&quot;pointer-events-auto ml-auto max-w-xl rounded-xl bg-white p-6 shadow-lg ring-1 ring-gray-900/10&quot;&gt;<br>            &lt;p class=&quot;text-sm/6 text-gray-900&quot;&gt;{{ $t(&#39;cookie.title&#39;) }} <br>                &lt;nuxt-link class=&quot;font-semibold text-secondary&quot; :to=&quot;localePath(&#39;cookie&#39;)&quot;&gt;<br>                    {{ $t(&#39;form.links.cookiePolicy&#39;) }}<br>                &lt;/nuxt-link&gt;.<br>            &lt;/p&gt;<br>            &lt;div class=&quot;mt-4 flex items-center gap-x-5&quot;&gt;<br>                &lt;button type=&quot;button&quot;<br>                        class=&quot;rounded-md bg-gray-900 px-3 py-2 text-sm font-semibold text-white shadow-xs hover:bg-gray-700 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-gray-900&quot;<br>                        @click=&quot;handleAccept&quot;&gt;<br>                    {{ $t(&#39;form.buttons.acceptAll&#39;) }}<br>                &lt;/button&gt;<br>                &lt;button type=&quot;button&quot;<br>                        class=&quot;text-sm/6 font-semibold text-gray-900&quot;<br>                        @click=&quot;handleDeny&quot;&gt;<br>                    {{ $t(&#39;form.buttons.rejectAll&#39;) }}<br>                &lt;/button&gt;<br>            &lt;/div&gt;<br>        &lt;/div&gt;<br>    &lt;/div&gt;<br>&lt;/template&gt;</pre><h3>How It Works</h3><ul><li>showBanner: This reactive ref controls whether the banner is shown.<br> It listens to whether the user has already made a choice or whether the consent expired.</li><li>handleAccept() / handleDeny(): These functions update preferences through nuxt-simple-cookie-consent&#39;s API.</li><li>Lifecycle hooks like onConsentAccepted or onCategoryAccepted allow additional logic (e.g., analytics initialization).</li></ul><h3>7️⃣ Registering the Component in Your Layout</h3><p>To ensure the banner appears globally, simply add your new component inside your main layout (usually layouts/default.vue):</p><pre>&lt;template&gt;<br>  &lt;NuxtLayout&gt;<br>    &lt;NuxtPage /&gt;<br>    &lt;CookieConsentBanner /&gt; &lt;!-- Your component --&gt;<br>  &lt;/NuxtLayout&gt;<br>&lt;/template&gt;</pre><p>This guarantees the banner will be available on every page.</p><h3>8️⃣ Create a Plugin to Manage Google Analytics Based on Consent</h3><p>Now, since we set initMode: &#39;manual&#39; for nuxt-gtag, we need a Nuxt plugin to initialize it only when consent is given.</p><p>Here’s the full plugin example:</p><pre>export default defineNuxtPlugin(() =&gt; {<br>    if (!process.client) return<br>  <br>    const { preferences, onConsentAccepted, onCategoryAccepted } = useCookieConsent()<br>    const { initialize } = useGtag()<br>  <br>    const initAnalytics = () =&gt; {<br>      if (process.env.NODE_ENV === &#39;production&#39;) {<br>        initialize()<br>        console.log(&#39;[gtag] initialized after user consent&#39;)<br>      }<br>    }<br>  <br>    if (preferences.value.analytics) {<br>      initAnalytics()<br>    }<br>  <br>    onConsentAccepted(() =&gt; {<br>      if (preferences.value.analytics) {<br>        initAnalytics()<br>      }<br>    })<br>  <br>    onCategoryAccepted((category) =&gt; {<br>      if (category === &#39;analytics&#39;) {<br>        initAnalytics()<br>      }<br>    })<br>})</pre><h3>Why This Works:</h3><ul><li>initialize() runs only after explicit user consent.</li><li>The plugin listens to both:</li><li><strong>Global consent</strong> (acceptAll)</li><li><strong>Per-category consent</strong> (analytics)</li><li>Everything is locked behind process.env.NODE_ENV === &#39;production&#39; to avoid analytics noise in development.</li></ul><h3>✅ Final Summary</h3><p>In this article, we walked through how to implement a <strong>GDPR-compliant cookie consent</strong> system in <strong>Nuxt.js 3</strong> using <a href="https://github.com/pentatrion-software/nuxt-simple-cookie-consent">nuxt-simple-cookie-consent</a> combined with nuxt-gtag for Google Analytics 4.</p><h3>Key takeaways:</h3><ul><li>We installed and configured the nuxt-simple-cookie-consent module to manage user preferences for cookies (analytics, ads, personalization) in a clear and user-friendly way.</li><li>We explicitly disabled automatic initialization of Google Analytics with initMode: &#39;manual&#39;.</li><li>We created a small, reusable Vue component to display a custom consent banner that respects both localization and accessibility.</li><li>We connected user consent choices with Google Analytics initialization via a Nuxt 3 plugin.</li></ul><p>Thanks to this approach, your Nuxt 3 app will:</p><ul><li>Respect modern privacy regulations (GDPR, ePrivacy).</li><li>Provide users with transparent control over their data.</li><li>Avoid initializing unnecessary tracking scripts until proper consent is given.</li></ul><h3>🚀 What’s Next?</h3><p>If you want to further improve this solution:</p><ul><li>Consider adding <strong>per-category scripts</strong> dynamically with onCategoryAccepted.</li><li>Implement server-side cookie checks if you’re running SSR with sensitive analytics.</li><li>Add more detailed <strong>logging and monitoring</strong> to track consent behavior (in a privacy-compliant way).</li></ul><h3>📌 Final Thoughts</h3><p>Nuxt 3 and its ecosystem offer all the tools you need to build privacy-first applications without sacrificing functionality.<br> Combining small utilities like nuxt-gtag and nuxt-simple-cookie-consent helps you stay compliant while keeping the developer experience clean and modular.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b1945a9c6ed2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Adding Google Popup Sign-In to Nuxt 3 (Continuing the Auth Flow)]]></title>
            <link>https://medium.com/@testjokerqwerty/adding-google-popup-sign-in-to-nuxt-3-continuing-the-auth-flow-8a6b95342111?source=rss-f904f2e9f03f------2</link>
            <guid isPermaLink="false">https://medium.com/p/8a6b95342111</guid>
            <category><![CDATA[google-popup]]></category>
            <category><![CDATA[nuxt-3]]></category>
            <category><![CDATA[google-auth]]></category>
            <category><![CDATA[nuxtjs]]></category>
            <dc:creator><![CDATA[Eugene Moskalenko]]></dc:creator>
            <pubDate>Sat, 12 Jul 2025 15:03:08 GMT</pubDate>
            <atom:updated>2025-07-12T15:03:08.979Z</atom:updated>
            <content:encoded><![CDATA[<p>In the previous article, we integrated <strong>Google One Tap Login</strong> into a Nuxt 3 application using <a href="https://github.com/srestraj/nuxt-vue3-google-signin">nuxt-vue3-google-signin</a> and <a href="https://github.com/trandaison/nuxt-3-auth">@trandaison/nuxt-3-auth</a>. Now, we’re continuing our authentication journey by adding <strong>Google Popup Login</strong> — the traditional OAuth flow where users choose their Google account via a modal popup.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/565/1*UC9CSOOU7qUhG12Laek1sA.png" /></figure><blockquote><em>📌 If you haven’t set up the required library yet, check the setup steps in the </em><a href="https://medium.com/@testjokerqwerty/adding-google-one-tap-login-in-nuxt-3-with-vue3-google-signin-7c2ab6000544"><em>previous article</em></a><em>.</em></blockquote><h3>🧩 What We Added in This Step</h3><p>In this commit, I:</p><ul><li>Added a <strong>login button</strong> on the home page (pages/index.vue)</li><li>Used useTokenClient() from vue3-google-signin to launch the <strong>Auth Code Flow</strong></li><li>Handled success and error callbacks</li><li>Used @trandaison/nuxt-3-auth to persist the user after login</li></ul><h3>🧪 Code Overview</h3><h4>📄 pages/index.vue</h4><pre>&lt;template&gt;<br>  &lt;section&gt;<br>    &lt;button<br>      :disabled=&quot;!isReady&quot;<br>      :loading=&quot;!isReady&quot;<br>      @click=&quot;() =&gt; loginGoogle()&quot;<br>    &gt;<br>      &lt;span&gt; google auth &lt;/span&gt;<br>    &lt;/button&gt;<br>  &lt;/section&gt;<br>&lt;/template&gt;</pre><p>This renders a simple login button that becomes active when the token client is ready.</p><h4>⚙️ Script Setup Logic</h4><pre>const { isReady, login: loginGoogle } = useTokenClient({<br>  onSuccess: handleOnSuccess,<br>  onError: handleOnError,<br>})</pre><p>The useTokenClient composable initiates the <strong>Google OAuth Code Flow</strong>, where the user selects their account in a popup.</p><h3>✅ Handling the Response</h3><pre>const handleOnSuccess = async (response) =&gt; {<br>  const res = await $api(&quot;/api/auth/google&quot;, {<br>    method: &quot;POST&quot;,<br>    body: response,<br>  })</pre><pre>  auth.storage.setAuth({<br>    token: res.access_token,<br>    refresh_token: res.refresh_token,<br>  })<br>  auth.storage.setPersistent(true)</pre><pre>  await auth.fetchUser()<br>  navigateTo(&quot;/private&quot;)<br>}</pre><p>Once Google returns a successful response:</p><ol><li>The response is sent to the backend (/api/auth/google)</li><li>The backend verifies the token and responds with access_token, refresh_token, and user data</li><li>Tokens are stored using @trandaison/nuxt-3-auth (auth.storage.setAuth(...))</li><li>The user is redirected to the protected area /private</li></ol><h3>🧪 Testing the Flow</h3><ol><li>Make sure your OAuth credentials in Google Cloud Console include:</li></ol><ul><li><strong>Authorized JavaScript origins</strong> (e.g. http://localhost:3000 or your ngrok domain)</li><li><strong>Authorized redirect URIs</strong> (even though popup mode doesn’t use redirection directly)</li></ul><ol><li>Use ngrok for local HTTPS testing:</li></ol><ul><li>bash</li><li>ngrok http 3000</li></ul><ol><li>Then use the ngrok URL in Google Cloud Console settings and .env.</li></ol><h3>📂 Source Code</h3><p>🔗 View the exact commit:<br> <a href="https://github.com/yevheniimoskalenko/nuxt-3-auth/commit/0db9c7b69aa036d9236572d42bc9750f500d8c69">https://github.com/yevheniimoskalenko/nuxt-3-auth/commit/0db9c7b69aa036d9236572d42bc9750f500d8c69</a></p><p>📁 Full project on GitHub:<br> <a href="https://github.com/yevheniimoskalenko/nuxt-3-auth">https://github.com/yevheniimoskalenko/nuxt-3-auth</a></p><p>🙌 Follow me on GitHub to stay updated:<br> <a href="https://github.com/yevheniimoskalenko">github.com/yevheniimoskalenko</a></p><p>🔜 Stay tuned! Next, we’ll explore handling logout, token refreshing, and protecting pages using Nuxt middleware.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8a6b95342111" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Adding Google One‑Tap Login in Nuxt 3 with vue3‑google‑signin]]></title>
            <link>https://medium.com/@testjokerqwerty/adding-google-one-tap-login-in-nuxt-3-with-vue3-google-signin-7c2ab6000544?source=rss-f904f2e9f03f------2</link>
            <guid isPermaLink="false">https://medium.com/p/7c2ab6000544</guid>
            <category><![CDATA[auth]]></category>
            <category><![CDATA[nuxt-3]]></category>
            <category><![CDATA[nuxtjs]]></category>
            <category><![CDATA[nuxtjs-3]]></category>
            <category><![CDATA[google-one-tap]]></category>
            <dc:creator><![CDATA[Eugene Moskalenko]]></dc:creator>
            <pubDate>Sat, 12 Jul 2025 14:30:15 GMT</pubDate>
            <atom:updated>2025-07-12T14:30:15.202Z</atom:updated>
            <content:encoded><![CDATA[<h3>nuxt‑vue3‑google‑signin, vue3‑google‑signin, and @trandaison/nuxt‑3‑auth</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/393/1*eHQZZBP9M17tHVJLRzL0sw.png" /></figure><p>In this commit, you implemented serverless Google One‑Tap sign-in in your Nuxt 3 app using two key libraries — <strong>nuxt‑vue3‑google‑signin</strong> (which wraps <strong>vue3‑google‑signin</strong>) for the frontend Google Identity interaction, and handled token storage/authentication flows with <strong>@trandaison/nuxt‑3‑auth</strong>.</p><h3>🔧 Libraries &amp; Motivation</h3><ul><li><strong>nuxt‑vue3‑google‑signin</strong> module seamlessly integrates the <strong>Google Identity Services</strong> (One‑Tap, Sign‑in) into Nuxt 3—auto-importing components, composables, and injecting script tags <a href="https://gist.github.com/srestraj/c61d0a025f53ab7f99bd875eace5cc84?utm_source=chatgpt.com">gist.github.com</a><a href="https://nuxt.com/modules/nuxt-vue3-google-signin?utm_source=chatgpt.com">youtube.com+15nuxt.com+15github.com+15</a><a href="https://deepwiki.com/wavezync/nuxt-vue3-google-signin?utm_source=chatgpt.com">deepwiki.com</a>.</li><li><strong>vue3‑google‑signin</strong> underpins the module, offering composables and plugin support for Vue 3 &amp; One‑Tap .</li><li><strong>@trandaison/nuxt‑3‑auth</strong> manages token persistence (access/refresh), user state, reactive middleware, and route protections .</li></ul><p>By combining them, the commit enables secure Google One‑Tap login, then persists authenticated sessions using the auth.login(...) flow via @trandaison/nuxt‑3‑auth.</p><h3>🧩 How The Flow Works in This Commit</h3><ol><li><strong>Install &amp; Configure the Module</strong></li></ol><pre>&quot;@trandaison/nuxt-3-auth&quot;: &quot;^0.2.0&quot;,<br>&quot;nuxt-vue3-google-signin&quot;: &quot;.0.11&quot;,<br>&quot;vue3-google-signin&quot;: &quot;.1.1&quot;</pre><ul><li>// nuxt.config.ts modules: [&#39;nuxt-vue3-google-signin&#39;, &#39;@trandaison/nuxt-3-auth&#39;], googleSignIn: { clientId: process.env.NUXT_PUBLIC_GOOGLE_CLIENT_ID }</li></ul><ol><li><strong>Inject the Google Script</strong><br> The module automatically adds &lt;script src=&quot;https://accounts.google.com/gsi/client&quot;&gt; to your app head, thanks to Nuxt&#39;s plugins <a href="https://deepwiki.com/wavezync/nuxt-vue3-google-signin/1.1-quick-start?utm_source=chatgpt.com">deepwiki.com</a><a href="https://gist.github.com/srestraj/c61d0a025f53ab7f99bd875eace5cc84?utm_source=chatgpt.com">gist.github.com</a>.</li><li><strong>In your login component/page:</strong></li></ol><pre>import { useOneTap, type CredentialResponse } from &quot;vue3-google-signin&quot;;<br>const auth = useAuth();<br>const { $auth } = useNuxtApp();<br>const { user, loggedIn } = $auth;<br>const head = useLocaleHead();<br>useOneTap({<br>  disableAutomaticPrompt: loggedIn.value,<br>  onSuccess: async (response: CredentialResponse) =&gt; {<br>    try {<br>      const res = await $api(&quot;/api/auth/google-one-tap&quot;, {<br>        method: &quot;POST&quot;,<br>        body: response as CredentialResponse,<br>      });<br>      auth.storage.setAuth({<br>        token: res.access_token,<br>        refresh_token: res.refresh_token,<br>      });<br>      auth.storage.setPersistent(true);<br>      auth.storage.setUser({ ...res.user, token: res.access_token }); // if you have user info get with sign up, you can use that, or if you don&#39;t have user info use await auth.fetchUser()<br>      auth.setReferer(null);<br>      await navigateTo(&quot;/private&quot;);<br>    } catch (err) {<br>      console.error(err);<br>    }<br>  },<br>  onError: () =&gt; console.error(&quot;Error with One Tap Login&quot;),<br>});</pre><ol><li>useOneTap() triggers the prompt and calls your handler on success/error. The secure credentials are passed to your API.</li><li><strong>User Persistence via </strong><strong>@trandaison/nuxt‑3‑auth</strong><br> After receiving tokens and user info from /api/auth/google-one-tap, you call auth.login(...). This ensures:</li></ol><ul><li>Tokens are stored (securely via Nuxt auth middleware),</li><li>Reactive auth.user state is maintained,</li><li>Middlewares protect routes based on authentication <a href="https://github.com/wavezync/nuxt-vue3-google-signin/issues/23?utm_source=chatgpt.com">github.com</a><a href="https://gist.github.com/srestraj/eed9d2f199ac4024e029e3012ff2829b?utm_source=chatgpt.com">builtatlightspeed.com+2gist.github.com+2vuejsexamples.com+2</a>.</li></ul><h3>🧪 Local Testing with ngrok</h3><p>To test Google One‑Tap locally, your redirect_uris and origin must be registered with Google, pointing to your <strong>ngrok</strong> tunnel:</p><ol><li>Run your Nuxt app: npm run dev.</li><li>Serve it via ngrok:</li></ol><ul><li>bash</li><li>ngrok http 3000</li><li>Copy the generated https://xxxx.ngrok.io URL.</li></ul><ol><li>In Google Cloud Console → OAuth 2.0 credentials:</li></ol><p>Add https://xxxx.ngrok.io to <strong>Authorized JavaScript origins</strong>,</p><ul><li>Add https://xxxx.ngrok.io/api/auth/google-one-tap (if used server-side) to <strong>Authorized redirect URIs</strong>.</li></ul><ol><li>Update .env:</li></ol><ul><li>NUXT_PUBLIC_GOOGLE_CLIENT_ID=your‑id.apps.googleusercontent.com</li></ul><ol><li>Start the app and test the One‑Tap popup on your ngrok URL. All authentication flows (client → Google → backend → Nuxt auth) should work end-to-end — mimicking production.</li></ol><h3>✅ Summary</h3><p>This commit delivers a fully acheivable Google One‑Tap login flow in Nuxt 3:</p><ul><li>Leveraging nuxt‑vue3‑google‑signin/vue3‑google‑signin simplifies frontend Google integration.</li><li>Persistent authentication is ensured by @trandaison/nuxt‑3‑auth.</li><li>Local testing with ngrok helps validate everything securely under HTTPS.</li></ul><p>This setup provides users with a polished, seamless login and developers with maintainable, progressive architecture.</p><p>👉 You can find the <strong>working code</strong> in my GitHub repo:<br> 🔗 <a href="https://github.com/yevheniimoskalenko/nuxt-3-auth">https://github.com/yevheniimoskalenko/nuxt-3-auth</a></p><p>📌 Direct link to the commit with full One Tap integration:<br> 🔗 <a href="https://github.com/yevheniimoskalenko/nuxt-3-auth/commit/785790298faf5339916a6fa4a16ca39462e9af5b">https://github.com/yevheniimoskalenko/nuxt-3-auth/commit/785790298faf5339916a6fa4a16ca39462e9af5b</a></p><p>🙌 Feel free to <strong>follow me</strong> on GitHub for more Nuxt 3, Vue, and fullstack experiments!<br> 👤 <a href="https://github.com/yevheniimoskalenko">github.com/yevheniimoskalenko</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7c2ab6000544" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating a Route Between Two Points with Google Maps and vue.js 3/Nuxt.js 3]]></title>
            <link>https://medium.com/@testjokerqwerty/creating-a-route-between-two-points-with-google-maps-and-vue-js-3-nuxt-js-3-3f6106fa0aa3?source=rss-f904f2e9f03f------2</link>
            <guid isPermaLink="false">https://medium.com/p/3f6106fa0aa3</guid>
            <category><![CDATA[nuxt]]></category>
            <category><![CDATA[google-maps]]></category>
            <category><![CDATA[nuxtjs-3]]></category>
            <category><![CDATA[vue]]></category>
            <category><![CDATA[vuejs-3]]></category>
            <dc:creator><![CDATA[Eugene Moskalenko]]></dc:creator>
            <pubDate>Fri, 18 Apr 2025 08:27:16 GMT</pubDate>
            <atom:updated>2025-04-18T08:27:16.177Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/486/1*75evI0subSOmD6Yk3stdhg.png" /></figure><p>In our previous article, “How to Integrate Google Maps in a Nuxt 3 Project and Add Markers,” we explored the basics of setting up Google Maps in a Nuxt.js 3 application and adding markers to the map. Today, we’ll build upon that foundation and dive deeper into creating a route between two points on the map. This functionality is essential for applications that require navigation, route planning, or simply visualizing the path from one location to another.</p><p>By the end of this article, you’ll have a clear understanding of how to calculate and display a route between two points using Google Maps and Nuxt.js 3. Let’s get started!</p><h3>Complete Code Explanation</h3><p>Below is the complete code for creating a route between two points using Google Maps and Nuxt.js 3. This code sets up a Google Map, calculates the route between two specified points, and handles cases where the route calculation might fail.</p><pre>&lt;template&gt;<br>  &lt;section&gt;<br>    &lt;GoogleMap<br>      ref=&quot;mapRef&quot;<br>      :api-key=&quot;GMAPS_API_KEY&quot;<br>      :options=&quot;mapOptions&quot;<br>      :center=&quot;center&quot;<br>      style=&quot;width: 100%; height: 100vh;&quot;<br>      :zoom=&quot;15&quot;<br>    /&gt;<br>  &lt;/section&gt;<br>&lt;/template&gt;</pre><pre>&lt;script setup lang=&quot;ts&quot;&gt;<br>import { GoogleMap } from &#39;vue3-google-map&#39;<br>import { ref, reactive, computed, watch } from &#39;vue&#39;<br>import { useRuntimeConfig } from &#39;nuxt/app&#39;<br>const env = useRuntimeConfig()<br>const mapRef = ref(null)<br>const GMAPS_API_KEY = computed(() =&gt; env.public.GMAPS_API_KEY)<br>const gmap = ref(null)<br>const mapOptions = reactive({<br>  zoom: 20,<br>  maxZoom: 10,<br>  minZoom: 3,<br>  styles: [],<br>})<br>const directionsRenderer = ref(null)<br>const center = computed(() =&gt; ({ lat: 50.4503596, lng: 30.5245025 }))<br>watch(<br>  () =&gt; mapRef.value?.ready,<br>  (ready) =&gt; {<br>    if (!ready) return<br>    gmap.value = mapRef.value.map<br>    directions()<br>  },<br>)<br>function setDirection(val) {<br>  directionsRenderer.value = val<br>}<br>async function directions() {<br>  try {<br>    const request = {<br>      origin: { lat: 50.44997703171514, lng: 30.521648629608134 }, // Start point<br>      destination: { lat: 49.81821975302162, lng: 24.01924069946072 }, // End point<br>      travelMode: &#39;DRIVING&#39;, // Travel mode: DRIVING, WALKING, BICYCLING, TRANSIT<br>    }<br>    const directionsService = new window.google.maps.DirectionsService()<br>    await directionsService.route(request, (response, status) =&gt; {<br>      if (status === window.google.maps.DirectionsStatus.OK) {<br>        if (!directionsRenderer.value) {<br>          setDirection(new window.google.maps.DirectionsRenderer())<br>          directionsRenderer.value.setMap(gmap.value)<br>        }<br>        directionsRenderer.value.setDirections(response)<br>      } else {<br>        console.error(&#39;Failed to calculate the route:&#39;, status)<br>        alert(&#39;No route found. Please check your coordinates and travel mode.&#39;)<br>      }<br>    })<br>  } catch (e) {<br>    console.log(e)<br>  }<br>}<br>&lt;/script&gt;</pre><h3>Explanation of the Code</h3><h3>Template Section</h3><ul><li><strong>GoogleMap Component</strong>:</li><li>ref=&quot;mapRef&quot;: A reference to the GoogleMap component, which allows us to access the map instance.</li><li>:api-key=&quot;GMAPS_API_KEY&quot;: Binds the Google Maps API key from the environment configuration.</li><li>:options=&quot;mapOptions&quot;: Sets the map options, such as zoom levels and styles.</li><li>:center=&quot;center&quot;: Sets the initial center of the map.</li><li>style=&quot;width: 100%; height: 100vh;&quot;: Sets the style of the map to take up the full width and height of the viewport.</li><li>:zoom=&quot;15&quot;: Sets the initial zoom level of the map.</li></ul><h3>Script Section</h3><ul><li><strong>Imports</strong>:</li><li>GoogleMap: Imported from vue3-google-map to render the Google Map.</li><li>ref, reactive, computed, watch: Imported from Vue to manage reactivity.</li><li>useRuntimeConfig: Imported from Nuxt to access environment variables.</li><li><strong>Variables and Reactive Properties</strong>:</li><li>env: Accesses the runtime configuration.</li><li>mapRef: A reference to the GoogleMap component.</li><li>GMAPS_API_KEY: Computed property to get the Google Maps API key from the environment configuration.</li><li>gmap: A reference to the Google Map instance.</li><li>mapOptions: Reactive object holding the map options such as zoom levels and styles.</li><li>directionsRenderer: A reference to the DirectionsRenderer instance.</li><li>center: Computed property to set the initial center of the map.</li><li><strong>Watcher</strong>:</li><li>Watches the ready state of the map and calls the directions function when the map is ready.</li><li><strong>Functions</strong>:</li><li>setDirection(val): Sets the DirectionsRenderer instance.</li><li>directions(): Calculates the route using the Google Maps DirectionsService and updates the map with the route.</li><li>request: Object containing the origin, destination, and travel mode for the route.</li><li>directionsService: Instance of the Google Maps DirectionsService.</li><li>route(request, (response, status) =&gt; {...}): Calculates the route and handles the response.</li><li>If the route calculation is successful (status === window.google.maps.DirectionsStatus.OK), it sets the directions on the map.</li><li>If the route calculation fails, it logs an error and alerts the user.</li></ul><h3>Conclusion</h3><p>This code provides a complete example of how to create a route between two points using Google Maps and Nuxt.js 3. It handles the setup of the map, the calculation of the route, and the rendering of the route on the map. Additionally, it includes error handling to alert the user if the route calculation fails. This functionality is essential for applications that require navigation, route planning, or simply visualizing the path from one location to another.</p><p>If you found this article helpful, please consider subscribing and leaving a comment to inspire more content like this. You can also check out the full code in the <a href="https://github.com/yevheniimoskalenko/nuxt-google-map/blob/master/pages/routes.vue">GitHub repository</a> and see a live demo <a href="https://nuxt3-google-map.netlify.app/routes">here</a>. Your feedback and support are greatly appreciated!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3f6106fa0aa3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Easy User sign in Nuxt 3 with @trandaison/nuxt-3-auth]]></title>
            <link>https://medium.com/@testjokerqwerty/easy-user-sign-in-nuxt-3-with-trandaison-nuxt-3-auth-77e0c67b83b9?source=rss-f904f2e9f03f------2</link>
            <guid isPermaLink="false">https://medium.com/p/77e0c67b83b9</guid>
            <category><![CDATA[nuxt-3]]></category>
            <category><![CDATA[nuxtjs]]></category>
            <category><![CDATA[nuxt]]></category>
            <category><![CDATA[sign-up]]></category>
            <dc:creator><![CDATA[Eugene Moskalenko]]></dc:creator>
            <pubDate>Fri, 07 Mar 2025 13:39:08 GMT</pubDate>
            <atom:updated>2025-03-07T13:39:08.791Z</atom:updated>
            <content:encoded><![CDATA[<h3>Easy User sign up in Nuxt 3 with @trandaison/nuxt-3-auth</h3><h3>Introduction to User Registration in Nuxt 3 with @trandaison/nuxt-3-auth</h3><p>In this article, we will delve into the process of implementing user registration in a Nuxt 3 application using the @trandaison/nuxt-3-auth module. This module simplifies the integration of authentication mechanisms, allowing developers to focus on building features rather than dealing with the intricacies of authentication logic.</p><p>We’ll walk through the steps required to set up user registration, ensuring that new users can create accounts seamlessly. Additionally, we’ll integrate an API plugin to handle requests and manage authentication tokens efficiently.</p><h3>Setting Up the API Plugin</h3><p>To facilitate communication with your backend API and handle authentication-related requests, we’ll create an API plugin. This plugin will use ofetch to make HTTP requests and manage tokens.</p><p>Here’s how you can set up the api.ts plugin:</p><pre>import { ofetch } from &#39;ofetch&#39;<br><br>export default defineNuxtPlugin((_nuxtApp) =&gt; {<br> const { $auth } = useNuxtApp()<br> const env = useRuntimeConfig()<br> const BaseURL = env.public.BaseURL<br> const $api = ofetch.create({<br>  credentials: &#39;include&#39;,<br>  baseURL: BaseURL,<br>  async onRequest({ options }) {},<br>  async onResponseError({ response }) {<br>   if (response.status === 401) {<br>    await $auth.refreshTokens()<br>   }<br>   return Promise.reject({<br>    status: response.status,<br>    message: response._data?.message || &#39;Unknown error&#39;,<br>   })<br>  },<br> })<br> globalThis.$api = $api<br>})</pre><h3>Explanation</h3><ul><li><strong>ofetch</strong>: A lightweight and flexible HTTP client used to make requests to your API.</li><li><strong>defineNuxtPlugin</strong>: Defines a Nuxt plugin that can be used to extend Nuxt’s functionality.</li><li><strong>useNuxtApp</strong>: Provides access to the Nuxt app instance, allowing us to use the $auth module.</li><li><strong>useRuntimeConfig</strong>: Accesses runtime configuration variables, such as the base URL for your API.</li><li><strong>onRequest</strong>: A hook that can be used to modify requests before they are sent.</li><li><strong>onResponseError</strong>: A hook that handles errors in responses, such as a 401 Unauthorized error, by attempting to refresh the authentication tokens.</li></ul><p>With this setup, your Nuxt 3 application is ready to handle API requests and manage authentication tokens efficiently. In the following sections, we’ll integrate this plugin into the registration process to ensure new users can sign up smoothly.</p><h3>Extending Nuxt 3 with Type Declarations</h3><p>To ensure type safety and improve developer experience, we can extend Nuxt 3’s type declarations. This allows us to use custom properties like $api and $toast with proper TypeScript support.</p><p>Here’s how you can extend the Nuxt 3 types by creating a types/nuxt.d.ts file:</p><pre>import { FetchInstance } from &#39;ofetch&#39;<br><br>declare module &#39;#app&#39; {<br> interface NuxtApp {<br>  $api: FetchInstance<br> }<br>}<br><br>declare global {<br> const $api: FetchInstance<br>}<br><br>export {}</pre><h3>Explanation</h3><ul><li><strong>FetchInstance</strong>: A type from ofetch that represents the instance used to make HTTP requests.</li><li><strong>declare module ‘#app’</strong>: Extends the Nuxt app module to include custom properties ($api and $toast) with their respective types.</li><li><strong>declare global</strong>: Declares global variables so that $api can be accessed globally within your application.</li><li><strong>export {}</strong>: Ensures that this file is treated as a module, which is necessary for TypeScript to recognize the type declarations.</li></ul><p>By extending the Nuxt 3 types, you ensure that your custom properties are recognized throughout your application, providing better autocompletion and type checking in your development environment. This setup is crucial for maintaining a robust and scalable codebase, especially as your application grows.</p><h3>Creating the Sign-Up Page in Nuxt 3</h3><p>To enable user registration in your Nuxt 3 application, we’ll create a sign-up.vue page. This page will handle the form submission and communicate with your backend API to register new users.</p><p>Here’s how you can set up the sign-up.vue page with the necessary script logic:</p><pre>&lt;script setup lang=&quot;ts&quot;&gt;<br>const auth = useAuth()<br>const credentials = reactive({<br> email: &#39;&#39;,<br> password: &#39;&#39;,<br> firstName: &#39;&#39;,<br> lastName: &#39;&#39;,<br> phoneNumber: &#39;&#39;,<br>})<br>definePageMeta({<br> auth: &#39;guest&#39;,<br>})<br><br>const signUp = async () =&gt; {<br> try {<br>  const res = await $api(&#39;/api/auth/sign-up&#39;, {<br>   method: &#39;POST&#39;,<br>   body: JSON.stringify({<br>    email: credentials.email,<br>    password: credentials.password,<br>    firstName: credentials.firstName,<br>    lastName: credentials.lastName,<br>    phoneNumber: credentials.phoneNumber.replace(/[() ]*/gi, &#39;&#39;),<br>    role: &#39;PLAYER&#39;,<br>    tariff: &#39;1&#39;,<br>   }),<br>  })<br>  auth.storage.setAuth({ token: res.access_token, refresh_token: res.refresh_token })<br>  auth.storage.setPersistent(true)<br>  // auth.storage.setUser(res.user) // Uncomment if you receive user info upon sign-up<br>  await auth.fetchUser()<br>  auth.setReferer(null)<br>  navigateTo(&#39;/private&#39;)<br> } catch (err) {<br>  console.error(err)<br> }<br>}<br>&lt;/script&gt;</pre><h3>Explanation</h3><ul><li><strong>useAuth()</strong>: Hook to access authentication-related methods and properties.</li><li><strong>reactive()</strong>: Creates a reactive object to store user credentials. This allows Vue to track changes and update the UI accordingly.</li><li><strong>definePageMeta()</strong>: Defines metadata for the page, specifying that this page is accessible to guests (non-authenticated users).</li><li><strong>signUp()</strong>: Asynchronous function that handles the sign-up process:</li><li>Sends a POST request to the /api/auth/sign-up endpoint with user credentials.</li><li>Stores the received tokens using auth.storage.setAuth().</li><li>Sets the authentication state to persistent.</li><li>Fetches user information using auth.fetchUser().</li><li>Redirects the user to the /private page upon successful registration.</li><li><strong>Error Handling</strong>: Catches and logs any errors that occur during the sign-up process.</li></ul><p>This setup ensures that new users can register smoothly, with their authentication tokens and user information managed appropriately. The use of reactive properties and async/await syntax helps maintain a clean and efficient codebase.</p><h3>Creating the Sign-Up Form Template</h3><p>The template for the sign-up.vue page will include a form where users can enter their registration details. This form will be bound to the reactive credentials object, allowing Vue to track and update the data as users interact with the form.</p><p>Here’s how you can set up the template for the sign-up page:</p><pre>&lt;template&gt;<br> &lt;section&gt;<br>  &lt;form @submit.prevent=&quot;signUp&quot;&gt;<br>   &lt;input<br>    v-model=&quot;credentials.email&quot;<br>    type=&quot;email&quot;<br>    placeholder=&quot;Email&quot;<br>   /&gt;<br>   &lt;input<br>    v-model=&quot;credentials.password&quot;<br>    type=&quot;password&quot;<br>    placeholder=&quot;Password&quot;<br>   /&gt;<br>   &lt;input<br>    v-model=&quot;credentials.firstName&quot;<br>    type=&quot;text&quot;<br>    placeholder=&quot;First Name&quot;<br>   /&gt;<br>   &lt;input<br>    v-model=&quot;credentials.lastName&quot;<br>    type=&quot;text&quot;<br>    placeholder=&quot;Last Name&quot;<br>   /&gt;<br>   &lt;input<br>    v-model=&quot;credentials.phoneNumber&quot;<br>    type=&quot;text&quot;<br>    placeholder=&quot;Phone Number&quot;<br>   /&gt;<br>   &lt;button type=&quot;submit&quot;&gt;Sign up&lt;/button&gt;<br>  &lt;/form&gt;<br> &lt;/section&gt;<br>&lt;/template&gt;</pre><h3>Explanation</h3><ul><li><strong>form</strong>: The form element uses @submit.prevent=&quot;signUp&quot; to call the signUp method when the form is submitted, preventing the default form submission behavior.</li><li><strong>v-model</strong>: Binds each input field to a property in the credentials object, allowing for two-way data binding. This means that changes in the input fields automatically update the credentials object, and vice versa.</li><li><strong>input</strong>: Each input field corresponds to a piece of user information required for registration:</li><li><strong>email</strong>: Collects the user’s email address.</li><li><strong>password</strong>: Collects the user’s password.</li><li><strong>firstName</strong>: Collects the user’s first name.</li><li><strong>lastName</strong>: Collects the user’s last name.</li><li><strong>phoneNumber</strong>: Collects the user’s phone number.</li><li><strong>button</strong>: A submit button that triggers the form submission.</li></ul><p>This template provides a straightforward and user-friendly interface for users to register, ensuring that all necessary information is collected and submitted to the backend API for processing.</p><h3>Conclusion and Next Steps</h3><p>With the setup described above, you now have a fully functional user registration system in your Nuxt 3 application, leveraging the @trandaison/nuxt-3-auth module. This module simplifies the process of managing authentication, allowing you to focus on building other features of your application.</p><h3>Key Takeaways</h3><ul><li><strong>Flexible Form Integration</strong>: The registration form can be customized to fit your specific needs, collecting any additional user information required by your application.</li><li><strong>Seamless Authentication</strong>: The @trandaison/nuxt-3-auth module handles the complexities of token management and user sessions, ensuring a smooth user experience.</li><li><strong>Type Safety</strong>: By extending Nuxt 3’s type declarations, you maintain type safety and improve the developer experience.</li></ul><h3>Explore Further</h3><p>To see a complete example and dive deeper into the implementation, you can check out the repository on GitHub: <a href="https://github.com/yevheniimoskalenko/nuxt-3-auth">nuxt-3-auth</a>. This repository contains the full codebase and additional examples to help you integrate authentication into your Nuxt 3 projects.</p><h3>Stay Updated</h3><p>For more insights, tutorials, and updates on Nuxt 3 and authentication strategies, consider following us on <a href="https://medium.com/">Medium</a>. Staying connected will help you stay informed about the latest best practices and developments in the Nuxt ecosystem.</p><p>By following these steps and resources, you’ll be well-equipped to implement robust authentication systems in your Nuxt 3 applications.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=77e0c67b83b9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Tracking Google Maps Viewport in Nuxt 3 and Fetching Results from Algolia]]></title>
            <link>https://medium.com/@testjokerqwerty/tracking-google-maps-viewport-in-nuxt-3-and-fetching-results-from-algolia-d46b56598b15?source=rss-f904f2e9f03f------2</link>
            <guid isPermaLink="false">https://medium.com/p/d46b56598b15</guid>
            <category><![CDATA[nuxt-3]]></category>
            <category><![CDATA[algolia]]></category>
            <category><![CDATA[nuxt]]></category>
            <category><![CDATA[google-map-api]]></category>
            <dc:creator><![CDATA[Eugene Moskalenko]]></dc:creator>
            <pubDate>Thu, 06 Mar 2025 19:16:52 GMT</pubDate>
            <atom:updated>2025-03-06T19:16:52.724Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZWvyndemxIKHNwDtAbtNgQ.png" /></figure><p>When integrating interactive maps into web applications, one of the key challenges is dynamically updating content based on the visible map area. Whether you’re building a property search platform, a restaurant locator, or any location-based service, ensuring that users see relevant results as they navigate the map can greatly enhance user experience.</p><p>In this article, we’ll explore how to track the viewport of Google Maps within a Nuxt 3 application and fetch search results dynamically from Algolia based on the visible map area. By the end, you’ll have a seamless integration that updates search results in real time as users pan or zoom the map.</p><h3>Installing @nuxtjs/algolia</h3><p>Before diving into the implementation, let’s install the necessary package to connect our Nuxt 3 app with Algolia:</p><pre>npm install @nuxtjs/algolia</pre><p>Once installed, register the module inside your nuxt.config.ts:</p><pre>export default defineNuxtConfig({<br>  modules: [&#39;@nuxtjs/algolia&#39;],<br>  algolia: {<br>    applicationId: process.env.ALGOLIA_APP_ID,<br>    apiKey: process.env.ALGOLIA_SEARCH_API_KEY<br>  }<br>})</pre><p>Make sure to add your Algolia credentials to the .env file:</p><pre>ALGOLIA_APP_ID=your_algolia_application_id <br>ALGOLIA_SEARCH_API_KEY=your_algolia_search_api_key</pre><p>Now that Algolia is set up, let’s move on to integrating Google Maps and tracking the viewport.</p><h3>Implementing Google Maps and Algolia Search in Nuxt 3</h3><p>Now that we have @nuxtjs/algolia installed, let’s move on to integrating Google Maps and tracking the viewport to fetch relevant results from Algolia.</p><p>We’ll create a new component called search.vue, which will handle both rendering the map and displaying search results based on the visible area.</p><h3>Creating search.vue</h3><p>In your pages or components directory, create a new file search.vue and add the following code:</p><pre>&lt;script setup lang=&quot;ts&quot;&gt;<br>import { GoogleMap, Marker } from &#39;vue3-google-map&#39;<br><br>const env = useRuntimeConfig()<br>const { result, search } = useAlgoliaSearch(&#39;fields&#39;)<br>const markerRef = useTemplateRef(&#39;markerRef&#39;)<br>const mapRef = useTemplateRef(&#39;mapRef&#39;)<br><br>const GMAPS_API_KEY = computed(() =&gt; env.public.GMAPS_API_KEY)<br><br>const mapOptions = reactive({<br> zoom: 20,<br> maxZoom: 10,<br> minZoom: 3,<br> styles: [],<br>})<br><br>const center = computed(() =&gt; ({ lat: 50.4503596, lng: 30.5245025 }))<br>const locals = computed(() =&gt; result.value?.hits || [])<br><br>// Debounce function to limit API calls<br>function debounce(func, wait) {<br> let timeout;<br> return function (...args) {<br>  const later = () =&gt; {<br>   clearTimeout(timeout);<br>   func(...args);<br>  };<br>  clearTimeout(timeout);<br>  timeout = setTimeout(later, wait);<br> };<br>}<br><br>const debouncedHandleBoundsChanged = debounce(handleBoundsChanged, 300)<br><br>// Function to fetch data when the map viewport changes<br>async function handleBoundsChanged() {<br>    const gmap = mapRef.value.map<br> const bounds = gmap.getBounds()<br>    if (bounds) {<br>        const ne = bounds.getNorthEast()<br>        const sw = bounds.getSouthWest()<br>        const boundingBox = [<br>            sw.lat(), <br>            sw.lng(),<br>            ne.lat(),<br>            ne.lat() <br>        ]<br><br>        try {<br>            await search({<br>                query: &#39;&#39;,<br>                requestOptions: {<br>                    facetFilters: [&#39;enabled:true&#39;, &quot;status:success&quot;],<br>                    insideBoundingBox: [boundingBox],<br>                    aroundRadius: 50<br>                }<br>            })<br>        } catch (error) {<br>            console.error(&#39;Error during Algolia search&#39;, error)<br>        }<br>    }<br>}<br><br>// Watch for map readiness and attach the event listener<br>watch(<br> () =&gt; mapRef.value?.ready,<br> (ready) =&gt; {<br>  if (!ready) return<br>  const gmap = mapRef.value.map<br>  gmap.addListener(&#39;bounds_changed&#39;, debouncedHandleBoundsChanged)<br> },<br>)<br>&lt;/script&gt;<br><br>&lt;template&gt;<br>    &lt;section class=&quot;grid grid-cols-7&quot;&gt;<br>        &lt;!-- List of results --&gt;<br>        &lt;div class=&quot;col-span-1&quot;&gt;<br>            &lt;div v-for=&quot;item in locals&quot; :key=&quot;item.id&quot;&gt;<br>                &lt;nuxt-link :to=&quot;`https://playfun.com.ua/field/${item.id}`&quot;&gt;<br>                    &lt;h2&gt;{{ item.title }}&lt;/h2&gt;<br>                &lt;/nuxt-link&gt;<br>                &lt;address&gt;{{ item.address }} ({{ item._geoloc.lat }}, {{ item._geoloc.lng }})&lt;/address&gt;<br>            &lt;/div&gt;<br>        &lt;/div&gt;<br><br>        &lt;!-- Google Map --&gt;<br>        &lt;div class=&quot;col-span-6&quot;&gt;<br>            &lt;GoogleMap<br>                ref=&quot;mapRef&quot;<br>                :api-key=&quot;GMAPS_API_KEY&quot;<br>                :options=&quot;mapOptions&quot;<br>                :center=&quot;center&quot;<br>                style=&quot;width: 100%; height: 100vh;&quot;<br>                :zoom=&quot;15&quot;<br>            &gt;<br>                &lt;Marker<br>                    v-for=&quot;marker in locals&quot;<br>                    ref=&quot;markerRef&quot;<br>                    :key=&quot;marker.id&quot;<br>                    :options=&quot;{<br>                        position: {<br>                            lat: marker._geoloc.lat,<br>                            lng: marker._geoloc.lng<br>                        }<br>                    }&quot;<br>                /&gt;<br>            &lt;/GoogleMap&gt;<br>        &lt;/div&gt;<br>    &lt;/section&gt;<br>&lt;/template&gt;</pre><h3>Breaking Down the Implementation</h3><ol><li><strong>Google Maps Integration</strong><br>We are using the vue3-google-map library to render a map with dynamic markers. The map is initialized with a default center (lat: 50.4503596, lng: 30.5245025), and users can zoom or move around freely.</li><li><strong>Fetching Search Results from Algolia</strong></li></ol><ul><li>We use useAlgoliaSearch(&#39;fields&#39;) to retrieve search results from Algolia.</li><li>The locals computed property extracts search results from result.value.hits.</li></ul><p><strong>3. Tracking the Viewport</strong></p><ul><li>When users move or zoom the map, the bounds_changed event triggers.</li><li>We use a debounce function (debounce(handleBoundsChanged, 300)) to limit the number of API calls.</li><li>The handleBoundsChanged function retrieves the new map boundaries and sends a request to Algolia using insideBoundingBox to fetch relevant data.</li></ul><p><strong>4. Displaying Results</strong></p><ul><li>The left sidebar lists search results as clickable links, leading to individual details.</li><li>The map updates dynamically with markers corresponding to search results.</li></ul><h3>Conclusion</h3><p>By implementing this approach, we can dynamically filter search results based on the visible area of the Google Map. This ensures that users always see relevant results without the need for manual searches or filters. Whether you’re building a location-based service, a property search platform, or any interactive map-based application, this technique provides a seamless and efficient user experience.</p><p>Want to see it in action? Check out the live demo here:<br>🔗 <a href="https://nuxt3-google-map.netlify.app/"><strong>Live Demo</strong></a></p><p>Curious about the full code implementation? You can find the complete project on GitHub:<br>💻 <a href="https://github.com/yevheniimoskalenko/nuxt-google-map"><strong>GitHub Repository</strong></a></p><p>If you found this guide helpful, don’t forget to follow me for more Nuxt 3 and web development content! 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d46b56598b15" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>