Identifier 'module' has already been declared - amplify and nuxt 3 - vuejs3

I am getting an error in nuxt3 then setting up this amplify plugin. I am trying to add auth to nuxt3 via plugins
plugins/amplify.js
import Amplify, {withSSRContext} from 'aws-amplify';
export default defineNuxtPlugin((ctx) => {
const awsConfig = {
Auth: {
region: "ap-south-1",
userPoolId: "ap-south-1_#########",
userPoolWebClientId: "#####################",
authenticationFlowType: "USER_SRP_AUTH",
},
};
Amplify.configure({ ...awsConfig, ssr: true });
if (process.server) {
const { Auth } = withSSRContext(ctx.req);
return {
provide: {
auth: Auth,
},
};
}
return {
provide: {
auth: Auth,
},
};
}
[nuxt] [request error] Identifier 'module' has already been declared
at Loader.moduleStrategy (internal/modules/esm/translators.js:145:18)
at async link (internal/modules/esm/module_job.js:67:21)
Does anyone know what's going on?

Been facing this myself... I don't think its a nuxt problem but rather Vite.
I gave up on running the app on dev mode and just resorted to building the app and launching it. Also, in order to use aws-amplify with vite you need to apply some workarounds:
https://ui.docs.amplify.aws/vue/getting-started/troubleshooting
For the window statement (which only makes sense on the browser) you'll need to wrap that with an if statement. Added this to my plugin file
if (process.client) {
window.global = window;
var exports = {};
}
This will let you build the project and run it with npm run build . Far from ideal but unless someone knows how to fix that issue with dev in vite...
BTW, you can also just switch to webpack builder on nuxt settings and the issue goes away.
// https://v3.nuxtjs.org/api/configuration/nuxt.config
export default defineNuxtConfig({
builder: "webpack"
});

I think this might be a problem with auto imports of nuxt.
I added a ~/composables/useBucket.ts file which I used in ~/api. Same error started popping up the next day. After I moved ~/composables/useBucket.ts to ~/composablesServer/useBucket.ts issue disappeared.

Related

Sanity and NextJs -> TypeError: Cannot read properties of undefined (reading 'fetch')

Im trying to create a portfolio site for myself using sanity on the backend. The site is working and the DB is set up and working using Sanity studio, but I cant get it to connect properly on the backend using Next.
Here is my connection file:
import { createClient } from "next-sanity";
import createImageUrlBuilder from "#sanity/image-url";
export const client = createClient({
projectId: "p079sml5",
dataset: "production",
apiVersion: "2023-01-31",
useCdn: false,
});
I'll be hiding a lot of this in env files but for the purposes of debugging I've left the info in.
And here is one of my endpoints:
import { NextApiRequest, NextApiResponse } from "next";
import { groq } from "next-sanity";
import { client } from "sanity";
import { Social } from "./typings";
const query = groq`
*[_type == "social"]
`;
type Data = {
socials: Social[];
};
export default async function handler(
req: NextApiRequest,
res: NextApiResponse<Data>
) {
const socials: Social[] = await client.fetch(query);
res.status(200).json({ socials });
}
As per the title, when trying to make the call on http://localhost:3000/api/getSocials, I get the following error: error - TypeError: Cannot read properties of undefined (reading 'fetch')
at handler (webpack-internal:///(api)/./src/pages/api/getSocials.ts:15:70)
Fetch appears on the autofill, along with the other methods, so it would appear that its been imported "correctly". The error suggests that that its the client that is the issue but cant figure out why.
Thanks in advance
Ive tried, using my dev environment, with the associated project id etc but no joy.
UPDATE: Fixed, I just moved the client file into a different folder, and it worked
Follow this doc https://github.com/vercel/next.js/tree/canary/examples/cms-sanity
Or setup this repo in new folder and update it's config (/lib/config.js) file with your sanity details then check... previously it was worked for me.

Firebase Cloud Messaging SW integration with Svelte-Kit

Has anyone integrated Firebase Cloud Messaging with Svelte-Kit. My main issue is registering the firebase-messaging-sw.js. If placed in the static directory I get a 'Syntax Error for using import outside of a module'. I've tried adding the file to the src directory, and telling vite about it. My svelte.config.js looks like this.
import adapter from '#sveltejs/adapter-node';
import preprocess from 'svelte-preprocess';
/** #type {import('#sveltejs/kit').Config} */
const config = {
preprocess: preprocess(),
kit: {
adapter: adapter({
out: 'dist'
}),
csrf: {
checkOrigin: false,
},
files: {
serviceWorker: 'src/firebase-messaging-sw.js'
}
},
};
export default config;
I am testing using vite build && vite preview with no luck. I feel like i'm missing a simple config to keep the file at the root of the project.
The solution I found was to use 'importScripts' a service worker helper I wasn't aware of.
importScripts('https://www.gstatic.com/firebasejs/9.10.0/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/9.10.0/firebase-messaging.js');

Nuxt plugin not available in Vuex's 'this' in Firebase production (ERROR: this.$myPlugin is not a function)

I'm trying to upload my nuxt app to Firebase as cloud function. The problem is that in the nuxtServerInit action I'm trying to call a plugin function, which apparently is not yet defined at that moment, because an error is thrown: (ERROR: this.$myPlugin is not a function). The code works in dev mode, it's just after upload to Firebase it fails.
The setup is as follows:
myPlugin.js
let env, auth, app, $store;
export default (context, inject) => {
env = context.app.context.env;
auth = context.app.$fire.auth;
app = context.app;
$store = context.store;
inject('myPlugin', myPlugin);
};
async function myPlugin(...) {... }
nuxt.config.js
plugins: [
{ src: '~/plugins/myPlugin', mode: 'all' }, // with no mode specified it fails too
],
vuex index.js
export const actions = {
async nuxtServerInit({ dispatch, commit }, { req }) {
const tl = await dispatch("initAction");
return tl;
}
}
vuex someModule.js
const actions = {
initAction({ commit }) {
return this.$myPlugin(...).then(...) // this line throws '$myPlugin is not a function' error
}
}
What can be the reason for the different behaviour in dev and in prod modes and how could I fix the problem?
UPDATE:
After further testing I established that the problem is not caused by the nuxtServerInit timing. I moved the call of the initAction from nuxtServerInit to a page's created hook. However the same error appears: this.$query is not a function.
The problem occured, because js files were not getting fully loaded due to CORB errors caused by incorrect configuration. Details described in this question.

Next.js returns 500: internal server error in Production

Created a next.js full stack application. After production build when I run next start it returns 500 : internal server. I'm using environment varibles for hitting api.
env.development file
BASE_URL=http://localhost:3000
It was working fine in development
service.ts
import axios from 'axios';
const axiosDefaultConfig = {
baseURL: process.env.BASE_URL, // is this line reason for error?
headers: {
'Access-Control-Allow-Origin': '*'
}
};
const axio = axios.create(axiosDefaultConfig);
export class Steam {
static getGames = async () => {
return await axio.get('/api/getAppList');
};
}
Do you have a next.config.js file?
To add runtime configuration to your app open next.config.js and add the publicRuntimeConfig and serverRuntimeConfig configs:
module.exports = {
serverRuntimeConfig: {
// Will only be available on the server side
mySecret: 'secret',
secondSecret: process.env.SECOND_SECRET, // Pass through env variables
},
publicRuntimeConfig: {
// Will be available on both server and client
staticFolder: '/static',
},
}
To get access to the runtime configs in your app use next/config, like so:
import getConfig from 'next/config'
// Only holds serverRuntimeConfig and publicRuntimeConfig
const { serverRuntimeConfig, publicRuntimeConfig } = getConfig()
// Will only be available on the server-side
console.log(serverRuntimeConfig.mySecret)
// Will be available on both server-side and client-side
console.log(publicRuntimeConfig.staticFolder)
function MyImage() {
return (
<div>
<img src={`${publicRuntimeConfig.staticFolder}/logo.png`} alt="logo" />
</div>
)
}
export default MyImage
I hope this helps.
I dont think you have setup env.
You need to configure it for it to work. Try it without it and it should work fine!

Jest Test - The current environment does not support the specified persistence type

I use jest to run some test on my Create React App with Firebase Web SDK coupled with FirebaseUI
Whenever I try to run some tests with --env=jsdom - I run into :
The current environment does not support the specified persistence type. seems related to Auth
Are there any known related issue/workaround ? the code seems to work/compile properly aside from the tests.
Google didn't help much
Here is the test, pretty basic.
HAd to add import "firebase/storage"; because of this : firebase.storage() is not a function in jest test cases
Thanks in advance
import React from "react";
import Enzyme from "enzyme";
import Adapter from "enzyme-adapter-react-16";
import "firebase/storage";
import {filterIngredientsToRemove} from "./shoppingList-reducer";
Enzyme.configure({adapter: new Adapter()});
describe("", () => {
let shoppingList;
let recipeId;
beforeEach(() => {
shoppingList = {
shoppingListItems: {
"1234": {ingredientId: 987, name: "patate", recipeId: 1234},
"2345": {ingredientId: 987, name: "patate", recipeId: 5432}
},
shoppingListRecipes: {
"1234": {portion: 3}
}
};
recipeId = 1234;
});
it("should filter out the shoppinglistItems with the provided recipeId", () => {
const result = filterIngredientsToRemove(recipeId, shoppingList.shoppingListItems);
expect(result).toEqual([{ingredientId: 987, name: "patate", recipeId: 1234}]);
});
});
Are you setting persistence in your firebase config? Persistence is not supported in the test environment, so you can do something like this to circumvent it:
firebase.auth().setPersistence(process.env.NODE_ENV === 'test'
? firebase.auth.Auth.Persistence.NONE
: firebase.auth.Auth.Persistence.LOCAL);
I ran into this issue too. The problem seems to come from the firebaseui constructor, specifically this line of code in my app:
new firebaseui.auth.AuthUI(this.firebase.auth())
What I did to solve it was initialize the ui object only when actually using it to sign on, not just as a static (typescript) variable. This let me run jest tests that didn't try to sign on just fine.
private static ui: firebaseui.auth.AuthUI | undefined
static startAuthOnElement (selectorToUse: string, onSignedIn: () => void) {
if (this.ui === undefined) this.ui = new firebaseui.auth.AuthUI(this.firebase.auth())
// more code
}
This way all the code that doesn't call startAuthOnElement never runs the firebaseui constructor. This lets me run my jest tests just fine and auth still works in the app.

Resources