I attempted to add the Google Identity services script to nuxt.config.ts, which should expose window.google.
// https://v3.nuxtjs.org/api/configuration/nuxt.config
export default defineNuxtConfig({
/* snip /*
head: {
script: [
{ src: "https://accounts.google.com/gsi/client" },
],
},
});
However, when I try to use it inside of a component, google is undefined.
<script setup lang="ts">
/* snip */
onMounted(() => {
// google is not defined
google.accounts.id.initialize({
client_id: "id.apps.googleusercontent.com",
callback: signInNew,
});
google.accounts.id.renderButton(document.getElementById("signIn")!, {
type: "standard",
});
google.accounts.id.prompt();
});
</script>
Upon further inspection, I found that the script is not added to the head at all. How can I fix this?
You may try the following way.
export default defineNuxtConfig({
app: {
head: {
script: [
{ src: "https://accounts.google.com/gsi/client" },
],
},
}
});
Related
I'm trying to setup nuxt-socket-io on a Nuxt 3 project. I followed all the setup steps in the nuxt-socket-io documentation but it's throwing the following Error:
Cannot add property registeredWatchers, object is not extensible.
Does anyone know what it means? What I'm missing?
Here's what my code looks like:
nuxt.config.js:
export default defineNuxtConfig({
modules: [
'#nuxtjs/tailwindcss',
'nuxt-socket-io',
],
app: {
head: {
title: 'Nuxt Dojo',
meta: [
{ name: 'description', content: 'Everything about Nuxt 3'},
],
link: [
{ rel: 'stylesheet', href: 'https://fonts.googleapis.com/icon?family=Material+Icons'}
]
}
},
runtimeConfig: {
public: {
apiUrl: process.env.API_URL,
},
},
io: {
// module options
sockets: [{
name: 'main',
url: 'http://localhost:4000'
}]
},
})
pages/index.vue:
<template>
<div>
<h2 class="text-xl">Index</h2>
<p>This project should become a messaging app.</p>
</div>
</template>
<script setup>
const socket = useNuxtApp().$nuxtSocket({
name: 'main',
channel: '/',
emitTimeout: 1000,
});
/* Listen for events: */
socket.on('message', (msg, cb) => {
console.log({ msg, cb });
});
</script>
I am trying to load the mapboxgl stylesheet in my Nuxt 3.0.0-rc.8 app. Typically with a Vue projec I manually add it to the head of the index.html page.
However, that is not how you do in Nuxt 3 apparently. I've tried adding it to the head and css options in the nuxt.config.ts file, but neither got me there. I did notice that when I added it to the css array, it was added to my header but 'https://' was replaced with '_nuxt'.
I know I am missing something simple. Here is my config file:
export default defineNuxtConfig({
css: [
'~/assets/css/main.css',
],
build: {
postcss: {
postcssOptions: require('./postcss.config.js'),
},
},
buildModules: ['#pinia/nuxt'],
runtimeConfig: {
treesAPIKey: '',
public: {
baseURL: '',
mapToken: '',
},
},
head: { link: [{ rel: 'stylesheet', href: 'https://api.mapbox.com/mapbox-gl-js/v2.6.1/mapbox-gl.css' }] },
});
Use app.head instead of head.
import { defineNuxtConfig } from 'nuxt'
export default defineNuxtConfig({
app: {
head: {
link: [{ rel: 'stylesheet', href: 'https://api.mapbox.com/mapbox-gl-js/v2.6.1/mapbox-gl.css' }]
}
}
})
Does anyone know why am I getting Module should export a function: #turf/helpers when I add #turf/helpers to my buildModules in nuxt.config.js?
nuxt.config.js
// Plugins to run before rendering page: https://go.nuxtjs.dev/config-plugins
plugins: [
],
// Auto import components: https://go.nuxtjs.dev/config-components
components: true,
// Modules for dev and build (recommended): https://go.nuxtjs.dev/config-modules
buildModules: [
// https://go.nuxtjs.dev/tailwindcss
'#nuxtjs/tailwindcss',
'#turf/helpers'
],
// Modules: https://go.nuxtjs.dev/config-modules
modules: [
],
Am I adding the module to the wrong array?
FYI: the module is present within my package.json / dependencies. Thus, the installation went through.
// Component where import { point } from '#turf/helpers' returns undefined
<script>
import { defineComponent } from '#vue/composition-api';
import mapboxgl from 'mapbox-gl';
import { point } from '#turf/helpers'
export default defineComponent({
data () {
return {
geojson: {
'type': 'FeatureCollection',
'features': []
},
map: null,
}
},
mounted() {
this.initMapBox();
},
methods: {
// Initialize MapBox map
initMapBox: function() {
mapboxgl.accessToken = 'pk.eyJ1IjoiYWxleGFuZHJ1YW5hIiwiYSI6ImNrZTl3NzJ3bzIxNG4yc2w2aG03dHNkMDUifQ.xaSxrVMLZtfGAlWoGvB1PQ';
this.map = new mapboxgl.Map({
container: 'map',
style: 'mapbox://styles/alexandruana/cksxeq0637zjy17tcvd4h919d',
center: [22.253, 45.419],
zoom: 4
});
this.map.on('load', () => {
console.log('Map loaded.')
let point = point([22.253, 45.419]);
console.log(point)
this.map.addSource('points', {
type: 'geojson',
data: this.geojson
});
this.map.addLayer({
id: 'points',
type: 'circle',
source: 'points',
paint: {
'circle-radius': 8,
'circle-color': '#00a9e2'
},
filter: ['in', '$type', 'Point']
});
});
},
}
})
Importing it as a regular NPM package and using it without colliding with the same variable name fixed the issue!
Indeed, this was not a Nuxt module.
I followed this guide:
https://medium.com/#marcmintel/quickly-develop-static-websites-with-vuejs-a-headless-cms-and-graphql-bf64e75910d6
but when I run npm run dev I get error 401 on my localhost:3000
this is my nuxt.config.js
module.exports = {
/*
** Headers of the page
*/
head: {
title: 'hello-world',
meta: [
{ charset: 'utf-8' },
{ name: 'viewport', content: 'width=device-width, initial-scale=1' },
{ hid: 'description', name: 'description', content: 'Nuxt.js project' }
],
link: [
{ rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }
]
},
/*
** Customize the progress bar color
*/
loading: { color: '#3B8070' },
/*
** Build configuration
*/
build: {
/*
** Run ESLint on save
*/
extend (config, { isDev, isClient }) {
if (isDev && isClient) {
config.module.rules.push({
enforce: 'pre',
test: /\.(js|vue)$/,
loader: 'eslint-loader',
exclude: /(node_modules)/
})
}
}
},
modules: [
'#nuxtjs/apollo',
],
apollo: {
clientConfigs: {
default: {
httpEndpoint: 'https://graphql.datocms.com',
getAuth: () => 'Bearer XXXXXXXXXXXXX' //my apikey
}
}
}
}
And this is the vue file performing the query. I'm currently displaying nothing in the page but I still get the error.
<template>
<div>
All blog posts
</div>
</template>
<script>
import gql from 'graphql-tag'
export default {
apollo: {
allPosts: gql`{
allPosts{
title,
text,
slug
}
}`
}
}
</script>
The post data type is correctly defined in DatoCMS, I tested it with the API Explorer
Found the solution in the comments of the article.
You need to put your auth in a separate file like this and format it as follows:
~/apollo/config.js
export default function(context){
return {
httpEndpoint: ‘https://graphql.datocms.com',
getAuth:() => ‘my-token’ //Bearer is added by default
}
}
Then in nuxt.config.js
apollo:
apollo: {
clientConfigs: {
default: ‘~/apollo/config.js’
}
}
So I've started to try nuxt and I'm at a point where I need axios but I can't use nuxt's axios module.
Here's the files
nuxt.config.js
module.exports = {
generate: {
routes: ['/']
},
head: {
meta: [
{ charset: 'utf-8' },
{ name: 'viewport', content: 'width=device-width, initial-scale=1' },
{ hid: 'description', name: 'description', content: 'Flynd FMS' }
],
link: [
{ rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }
]
},
loading: { color: '#3B8070' },
modules: [
'#nuxtjs/router',
'#nuxtjs/dotenv'
],
plugins: [
{src: '#/plugins/axios.js', ssr: true},
{src: '#/plugins/vuex-router-sync.js', ssr: false}
],
build: {
vendor: ['axios'],
extend (config, ctx) {
if (ctx.dev && ctx.isClient) {
config.module.rules.push({
enforce: 'pre',
test: /\.(js|vue)$/,
loader: 'eslint-loader',
exclude: /(node_modules)/
})
}
}
}
}
plugins/axios.js
import axios from 'axios'
const instance = axios.create({
baseURL: process.env.API_HOST + ':' + process.env.API_PORT,
transformRequest: function (request) {
return request
}
})
export default instance
pages/Login.vue
<template>
</template>
<script>
</script>
In this state, the axios instance should have not been called even once, but strange thing that it produces an error page mentioning Request failed with status code 404
I suspected that it tried to hit axios's baseUrl, and I had it confirmed by checking nginx access log.
Is this an expected behavior? If not, can anyone point me how to avoid this?
Thanks!
Update
Okay, I got it working few minutes after posting this out by changing the ssr to false
nuxt.config.js
module.exports = {
plugins: [
{src: '#/plugins/axios.js', ssr: false}
]
}
But I'll keep this question open since that behavior in ssr mode still unexpected.
If you are using the latest version on nuxt.js it will which module to install.
Just Select the "Axios" by hitting space then you are good to go.
See Img here
Then you can make a global function for all your calls.
This is a global function for all get calls.
Don't forget to include this file in middleware folder.
getReq: async function (apiUrl, reqHeader) {
return await axios
.get(apiUrl, reqHeader)
.then((response) => {
console.log('Response from', apiUrl, ':', response)
return response
})
.catch((err) => {
if(err.response.data.error === 'session data missing'){
console.log("this:",this);
console.log("Error:",err.response.data.error);
// Popup Msg
Snackbar.open({
duration: 5000,
message: 'Session Error! Please Sign Again',
type: 'is-warning',
position: 'is-top-right',
actionText: 'Ok',
indefinite: false,
onAction: () => {
console.log("pap",location);
location.replace("/")
}
})
}
return err.response
})
},
This is how the global funtion is called.
const contractList = {
headers: {},
params: {
id: null,
state: this.state
},
withCredentials: true
}
const response = await ApiService.getReq(LIST_CONTRACT, contractList)
console.log('Response from getList', response)
The problem is with axios.
Handling of async request can cause this issue.
In my case, one of the external apis being used was down which was causing axios to fail.
Steps to debug and resolve this:
Identify where all is axios being used
Check if the apis are returning the correct response (check this outside of the project)
If required, comment apis and check which one if the api causing the issue
Additionally interceptors can be used to capture the error and show proper stack trace as done here