Adnan Erlansyah
Adnan Erlansyah
NNuxt
Created by Adnan Erlansyah on 1/17/2025 in #❓・help
Failed to exchange the Google token
Hello everyone, has anyone here ever encountered the error that the code from Google OAuth is not valid when I try to exchange it for a token from the backend? I followed this article to implement a login flow with Google using nuxt-utils, but when the code is sent to the backend, it becomes invalid, resulting in the error: failed to exchange Google token https://medium.com/@tony.infisical/guide-to-using-oauth-2-0-to-access-google-apis-dead94d6866d This is my code to handle login google oauth.
// @ts-nocheck
export default defineOAuthGoogleEventHandler({
config: {
authorizationURL: 'https://accounts.google.com/o/oauth2/auth',
tokenURL: 'https://oauth2.googleapis.com/token',
userURL: 'https://www.googleapis.com/oauth2/v3/userinfo',
authorizationParams: {
scope: 'email profile openid'
},
},
// @ts-ignore
async onSuccess(event) {
const query = await getQuery(event);
const code = query.code; // This code isn't valid when I sent to backend

console.log(query)
// Check if the data user is matched from the database
// If it's matched then then make user login else redirect user to register page
// Construct a script to close the popup and notify the parent
const closeScript = `
<script>
if (window.opener) {
window.opener.postMessage({ success: true, code: '${code}' }, '*');
window.close();
}
</script>
`;

// Return a response that runs the script
// return sendRedirect(event, '/auth/register')
return send(event, closeScript, 'text/html');
},
onError(event, error) {
console.error('Google OAuth error:', error);
// You can choose to send an error response instead of redirecting
return sendRedirect(event, '/')
},
})
// @ts-nocheck
export default defineOAuthGoogleEventHandler({
config: {
authorizationURL: 'https://accounts.google.com/o/oauth2/auth',
tokenURL: 'https://oauth2.googleapis.com/token',
userURL: 'https://www.googleapis.com/oauth2/v3/userinfo',
authorizationParams: {
scope: 'email profile openid'
},
},
// @ts-ignore
async onSuccess(event) {
const query = await getQuery(event);
const code = query.code; // This code isn't valid when I sent to backend

console.log(query)
// Check if the data user is matched from the database
// If it's matched then then make user login else redirect user to register page
// Construct a script to close the popup and notify the parent
const closeScript = `
<script>
if (window.opener) {
window.opener.postMessage({ success: true, code: '${code}' }, '*');
window.close();
}
</script>
`;

// Return a response that runs the script
// return sendRedirect(event, '/auth/register')
return send(event, closeScript, 'text/html');
},
onError(event, error) {
console.error('Google OAuth error:', error);
// You can choose to send an error response instead of redirecting
return sendRedirect(event, '/')
},
})
7 replies
NNuxt
Created by Adnan Erlansyah on 1/16/2025 in #❓・help
How to import component from inside the directory in NuxtJS 3?
How to import component from inside the directory in NuxtJS 3? so for example, I have a component SplashScreen on folder components/partials.
4 replies
NNuxt
Created by Adnan Erlansyah on 1/16/2025 in #❓・help
How to make splash screen effect in NuxtJS 3?
Hello everyone, Is NuxtJS 3 support to make splash screen effect like mobile app? so I want the splash screen to only appear once when the app is initialized for the first time.
39 replies
NNuxt
Created by Adnan Erlansyah on 1/15/2025 in #❓・help
Problem store on middleware
How to fix this issue in middleware?
[nitro] [unhandledRejection] [nuxt] A composable that requires access to the Nuxt instance was called outside of a plugin, Nuxt hook, Nuxt middleware, or Vue setup function. This is probably not a Nuxt bug. Find out more at https://nuxt.com/docs/guide/concepts/auto-imports#vue-and-nuxt-composables.
[nitro] [unhandledRejection] [nuxt] A composable that requires access to the Nuxt instance was called outside of a plugin, Nuxt hook, Nuxt middleware, or Vue setup function. This is probably not a Nuxt bug. Find out more at https://nuxt.com/docs/guide/concepts/auto-imports#vue-and-nuxt-composables.
This is my middleware.
import { callOnce } from "#app";
import { serviceStore } from "~/stores/service";
import useService from "~/composables/use-service";

export default defineNuxtRouteMiddleware(async (to, from) => {
// Ensure this code runs only once
await callOnce(async () => {
const service = serviceStore(); // Pinia store
const { setHealthCheck, getHealthCheck } = useService(); // Composable

// Check if health status is already cached in cookies
const cachedHealthStatus = getHealthCheck();
if (cachedHealthStatus !== null) {
// Set the status in the store from the cookie
service.status = cachedHealthStatus === "true";
return; // Skip API call if status is cached
}

try {
// Perform the health check API call
await service.getCheckHealthz();

// Save the status in cookies based on the API response
await setHealthCheck(service.status);
} catch (error) {
console.error("API Health Check Failed:", error);

// Mark the API as unhealthy and save in cookies
await setHealthCheck(false);

// Optionally throw an error to block the route if necessary
throw createError({
statusCode: 500,
statusMessage: "API is currently unavailable.",
});
}
});
});
import { callOnce } from "#app";
import { serviceStore } from "~/stores/service";
import useService from "~/composables/use-service";

export default defineNuxtRouteMiddleware(async (to, from) => {
// Ensure this code runs only once
await callOnce(async () => {
const service = serviceStore(); // Pinia store
const { setHealthCheck, getHealthCheck } = useService(); // Composable

// Check if health status is already cached in cookies
const cachedHealthStatus = getHealthCheck();
if (cachedHealthStatus !== null) {
// Set the status in the store from the cookie
service.status = cachedHealthStatus === "true";
return; // Skip API call if status is cached
}

try {
// Perform the health check API call
await service.getCheckHealthz();

// Save the status in cookies based on the API response
await setHealthCheck(service.status);
} catch (error) {
console.error("API Health Check Failed:", error);

// Mark the API as unhealthy and save in cookies
await setHealthCheck(false);

// Optionally throw an error to block the route if necessary
throw createError({
statusCode: 500,
statusMessage: "API is currently unavailable.",
});
}
});
});
5 replies
NNuxt
Created by Adnan Erlansyah on 1/14/2025 in #❓・help
How to to get the current url in NuxtJS 3
How to to get the current url from server-side in NuxtJS 3?
import { storeToRefs } from "pinia";
import authApi from "~/composables/api/authApi";

const { apiLoginGoogle } = authApi();

export default defineOAuthGoogleEventHandler({
config: {
authorizationURL: 'https://accounts.google.com/o/oauth2/v2/auth',
tokenURL: 'https://oauth2.googleapis.com/token',
userURL: 'https://www.googleapis.com/oauth2/v3/userinfo',
authorizationParams: {},
},
// @ts-ignore
async onSuccess(event, { user, tokens }) {
// Check if the data user is matched from the database
// If it's matched then then make user login else redirect user to register page
const payload = {
code: tokens?.access_token,
redirectUri:
}
const response = await apiLoginGoogle(payload);
console.log(response)
// Construct a script to close the popup and notify the parent
const closeScript = `
<script>
if (window.opener) {
window.opener.postMessage({ success: true, user: ${JSON.stringify(user)}, tokens: ${JSON.stringify(tokens)} }, '*');
window.close();
}
</script>
`;

// Return a response that runs the script
// return sendRedirect(event, '/auth/register')
return send(event, closeScript, 'text/html');
},
onError(event, error) {
console.error('Google OAuth error:', error);
// You can choose to send an error response instead of redirecting
return sendRedirect(event, '/')
},
})
import { storeToRefs } from "pinia";
import authApi from "~/composables/api/authApi";

const { apiLoginGoogle } = authApi();

export default defineOAuthGoogleEventHandler({
config: {
authorizationURL: 'https://accounts.google.com/o/oauth2/v2/auth',
tokenURL: 'https://oauth2.googleapis.com/token',
userURL: 'https://www.googleapis.com/oauth2/v3/userinfo',
authorizationParams: {},
},
// @ts-ignore
async onSuccess(event, { user, tokens }) {
// Check if the data user is matched from the database
// If it's matched then then make user login else redirect user to register page
const payload = {
code: tokens?.access_token,
redirectUri:
}
const response = await apiLoginGoogle(payload);
console.log(response)
// Construct a script to close the popup and notify the parent
const closeScript = `
<script>
if (window.opener) {
window.opener.postMessage({ success: true, user: ${JSON.stringify(user)}, tokens: ${JSON.stringify(tokens)} }, '*');
window.close();
}
</script>
`;

// Return a response that runs the script
// return sendRedirect(event, '/auth/register')
return send(event, closeScript, 'text/html');
},
onError(event, error) {
console.error('Google OAuth error:', error);
// You can choose to send an error response instead of redirecting
return sendRedirect(event, '/')
},
})
9 replies
NNuxt
Created by Adnan Erlansyah on 1/14/2025 in #❓・help
How to handle error messages based on enviroment?
Hello everyone, has anyone here ever experienced about how we can handle the error message based on environment? so for example if it's on dev, then the message will shown as from the debugging but when it's on production then use a message that looks informative like 'Server is being error now, please try again later'.
5 replies
NNuxt
Created by Adnan Erlansyah on 1/14/2025 in #❓・help
How to make a middleware Check Permission to access some page
How to make a middleware like Check permission to access some page, so we can send what the roles that can do some action. Something like this I think.
definePageMeta({
middleware: ['checkPermission:1']
})
definePageMeta({
middleware: ['checkPermission:1']
})
38 replies
NNuxt
Created by Adnan Erlansyah on 1/13/2025 in #❓・help
Why nuxt is so slow when refresh it at the second time
No description
5 replies
NNuxt
Created by Adnan Erlansyah on 1/9/2025 in #❓・help
How to integrate login with third party like facebook, instagram, etc in NuxtJS 3.
Integration login with third party by using NuxtJS 3
85 replies
NNuxt
Created by Adnan Erlansyah on 12/9/2024 in #❓・help
How to make prefix on FormKit?
How to make prefix on FormKit? without using formkit icon module
4 replies
NNuxt
Created by Adnan Erlansyah on 12/6/2024 in #❓・help
How to manage or change the size of LCircle?
How to manage or change the size of LCircle from nuxt module leaflet in NuxtJS3?
<LCircle
:lat-lng="[47.21322, -1.559482]"
:radius="4500"
:color="'red'"
/>
<LCircle
:lat-lng="[47.21322, -1.559482]"
:radius="4500"
:color="'red'"
/>
4 replies
NNuxt
Created by Adnan Erlansyah on 12/6/2024 in #❓・help
How the best way or easy to import a component on the page of NuxtJS3?
How the best way to import a component on the page of NuxtJS3?
9 replies
NNuxt
Created by Adnan Erlansyah on 12/6/2024 in #❓・help
Will the environment variables from the project can be fiddle on the browser by user?
Will the environment variables from the project can be fiddle on the browser by user?
10 replies
NNuxt
Created by Adnan Erlansyah on 12/5/2024 in #❓・help
How can I process some data on server-side and send it to the client-side
How can I process some data on server-side and send it to the client-side?
11 replies
NNuxt
Created by Adnan Erlansyah on 12/4/2024 in #❓・help
how to apply css modules to hash css selectors in nuxtjs3?
how to apply css modules to hash css selectors in nuxtjs3?
14 replies
NNuxt
Created by Adnan Erlansyah on 12/4/2024 in #❓・help
How to access data env in composable?
How to get data from env in composable?
30 replies
NNuxt
Created by Adnan Erlansyah on 12/3/2024 in #❓・help
what folder name is suitable for internalization
what folder name is suitable for internalization in nuxtjs3 ? should I put it on folder composable>constants or make it separately?
5 replies
NNuxt
Created by Adnan Erlansyah on 12/2/2024 in #❓・help
References for general topics or new updates of NuxtJS 3 or VueJS
Hi everyone, does anyone know of any YouTube channels that explain Nuxt.js or Vue.js, whether it's about general topics or new updates? If anyone knows, please let me know. Thank you.
6 replies
NNuxt
Created by Adnan Erlansyah on 12/2/2024 in #❓・help
Turn on Camera Light in NuxtJS3
How to turn on camera light in NuxtJS 3 or VueJS 3
4 replies
NNuxt
Created by Adnan Erlansyah on 11/27/2024 in #❓・help
Issue can't render other pages
How to fix this error from nuxtjs3.
WARN [nuxt] Your project has pages but the <NuxtPage /> component has not been used. You might be using the <RouterView /> component instead, which will not work correctly in Nuxt. You can set
pages: false in nuxt.config if you do not wish to use the Nuxt vue-router integration.
WARN [nuxt] Your project has pages but the <NuxtPage /> component has not been used. You might be using the <RouterView /> component instead, which will not work correctly in Nuxt. You can set
pages: false in nuxt.config if you do not wish to use the Nuxt vue-router integration.
14 replies