Failed to load static props with empty paths and fallback - next.js

I have the following code on my Dynamic Routing page [id] that I am trying to use with next-i18next translations. However, it is throwing an error when being deployed on Vercel (working locally). I am trying to use the fallback function with an empty path array to somehow accept all possible paths(?). In my console I am getting a statuscode 500 GET-error and a "Failed to load static props"-error.
It is working when I specify a specific id within getStaticPaths and go to that matching path. However, I can't possibly specify thousands of ids for this to work. Shouldn't the fallback take care of this or how can I get past this?
export async function getStaticPaths() {
return {
paths: [], fallback: true
}
}
export async function getStaticProps(context) {
return {
props: {
params: context.params,
...(await serverSideTranslations(context.locale, ["common"])),
},
}
}
Update:
This is the Vercel function log (xxxxx-values is some id's I removed)
[GET] /_next/data/xxxxxxxxxxx-y/en/packages/490713.json
20:26:37:98
2022-02-28T19:26:39.300Z xxxxxxxxxxxxxxxxxxxxx ERROR Error: ENOENT: no such file or directory, scandir '/var/task/public/locales/en'
at Object.readdirSync (fs.js:1047:3)
at getLocaleNamespaces (/var/task/node_modules/next-i18next/dist/commonjs/config/createConfig.js:175:23)
at /var/task/node_modules/next-i18next/dist/commonjs/config/createConfig.js:181:20
at Array.map (<anonymous>)
at getNamespaces (/var/task/node_modules/next-i18next/dist/commonjs/config/createConfig.js:180:44)
at createConfig (/var/task/node_modules/next-i18next/dist/commonjs/config/createConfig.js:221:29)
at _callee$ (/var/task/node_modules/next-i18next/dist/commonjs/serverSideTranslations.js:199:53)
at tryCatch (/var/task/node_modules/regenerator-runtime/runtime.js:63:40)
at Generator.invoke [as _invoke] (/var/task/node_modules/regenerator-runtime/runtime.js:294:22)
at Generator.next (/var/task/node_modules/regenerator-runtime/runtime.js:119:21) {
errno: -2,
syscall: 'scandir',
path: '/var/task/public/locales/en',
page: '/packages/[id]'
}
RequestId: xxxxxxxxxxxxxxxxxxxx Error: Runtime exited with error: exit status 1
Runtime.ExitError

This line was missing in my next-i18next-config
localePath: path.resolve('./public/locales'),

Related

What is the best practice to bypass my specific dynamic code evaluation in next.js middleware?

I use next.js middleware to retrieve a data stored inside a cookie, and to check in a db (using strapi) if this specific user exists, or if he needs to register before going further.
// middleware.js
import { getToken } from 'next-auth/jwt';
import qs from 'qs';
import { MY_DB } from './constants';
export async function middleware(request) {
const token = await getToken({
req: request,
secret: process.env.SECRET,
});
const params = qs.stringify({
filters: {
address: {
$eq: token.sub,
},
},
});
const url = MY_DB + '/api/users/?' + params;
const result = await fetch(url, {
method: 'GET',
headers: { accept: 'application/json' },
});
// remaining code checks if the request is empty or not and returns the appropriate page
(...)
building my project returns the following error :
Failed to compile.
./node_modules/.pnpm/function-bind#1.1.1/node_modules/function-bind/implementation.js
Dynamic Code Evaluation (e. g. 'eval', 'new Function', 'WebAssembly.compile') not allowed in Edge Runtime
Learn More: https://nextjs.org/docs/messages/edge-dynamic-code-evaluation
Import trace for requested module:
./node_modules/.pnpm/function-bind#1.1.1/node_modules/function-bind/implementation.js
./node_modules/.pnpm/function-bind#1.1.1/node_modules/function-bind/index.js
./node_modules/.pnpm/get-intrinsic#1.1.3/node_modules/get-intrinsic/index.js
./node_modules/.pnpm/side-channel#1.0.4/node_modules/side-channel/index.js
./node_modules/.pnpm/qs#6.11.0/node_modules/qs/lib/stringify.js
./node_modules/.pnpm/qs#6.11.0/node_modules/qs/lib/index.js
> Build failed because of webpack errors
 ELIFECYCLE  Command failed with exit code 1.
I highly suspect the qs.stringify call given the stacktrace, but how can I overcome this in an elegant way ?

Login attempt with GoogleProvider in next-auth returns OAUTH_CALLBACK_ERROR and message: checks.state argument is missing

I'm on a project for my JS FullStack course and I'm running into some issues with Google Provider of next-auth (version 4.18.8).
Everything worked fine ONE SINGLE TIME this morning. After successfuly login with google provider and use "useSession()" to get the Google credentials in a console.log, I committed everything and went to the gym. After I get back (and took a shower, of course), I was going to get those google credentials to show the user name on the page's header, but to my surprise I started getting this callback error.
FYI, env.local is correcty setup with GOOGLE_CLIENT_ID and GOOGLE_CLIENT_SECRET. I even deleted my credentials on Google and created another one to test, but no luck.
When trying to login, I get this error:
[next-auth][error][OAUTH_CALLBACK_ERROR]
https://next-auth.js.org/errors#oauth_callback_error checks.state argument is missing {
error: TypeError: checks.state argument is missing
at Client.callback (C:\João\Dropbox\Pessoal\Projetos Webdesign\trading-center\node_modules\openid-client\lib\client.js:387:13)
at oAuthCallback (C:\João\Dropbox\Pessoal\Projetos Webdesign\trading-center\node_modules\next-auth\core\lib\oauth\callback.js:127:29)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
at async Object.callback (C:\João\Dropbox\Pessoal\Projetos Webdesign\trading-center\node_modules\next-auth\core\routes\callback.js:52:11)
at async AuthHandler (C:\João\Dropbox\Pessoal\Projetos Webdesign\trading-center\node_modules\next-auth\core\index.js:201:28)
at async NextAuthHandler (C:\João\Dropbox\Pessoal\Projetos Webdesign\trading-center\node_modules\next-auth\next\index.js:23:19)
at async C:\João\Dropbox\Pessoal\Projetos Webdesign\trading-center\node_modules\next-auth\next\index.js:59:32
at async Object.apiResolver (C:\João\Dropbox\Pessoal\Projetos Webdesign\trading-center\node_modules\next\dist\server\api-utils\node.js:363:9)
at async DevServer.runApi (C:\João\Dropbox\Pessoal\Projetos Webdesign\trading-center\node_modules\next\dist\server\next-server.js:487:9)
at async Object.fn (C:\João\Dropbox\Pessoal\Projetos Webdesign\trading-center\node_modules\next\dist\server\next-server.js:749:37)
at async Router.execute (C:\João\Dropbox\Pessoal\Projetos Webdesign\trading-center\node_modules\next\dist\server\router.js:253:36)
at async DevServer.run (C:\João\Dropbox\Pessoal\Projetos Webdesign\trading-center\node_modules\next\dist\server\base-server.js:384:29)
at async DevServer.run (C:\João\Dropbox\Pessoal\Projetos Webdesign\trading-center\node_modules\next\dist\server\dev\next-dev-server.js:741:20)
at async DevServer.handleRequest (C:\João\Dropbox\Pessoal\Projetos Webdesign\trading-center\node_modules\next\dist\server\base-server.js:322:20) {
name: 'OAuthCallbackError',
code: undefined
},
providerId: 'google',
message: 'checks.state argument is missing'
There are some things I noticed after clicking in my Google account, on Network tab of my DevTools:
First, it will make a request that returns status code 302 on "consent?authuser=0&part=......."
After that, another request to "google?state=......" returns 302 also.
Then I get an error on request to http://127.0.0.1:3000/api/auth/error?error=OAuthCallback also with 302 status code.
Finally, I get an error on request to http://127.0.0.1:3000/api/auth/signin?error=OAuthCallback that returns 404
I don't understand this very much, but I'm pretty sure I was not meant to get a 302 error on those requests.
Here's my code.
I have a button that calls this function:
const handleGoogleLogin = async () => {
await signIn('google', {
redirect: true,
callbackUrl: 'http://127.0.0.1:3000/user/dashboard'
})
}
My [...nextauth].js file:
export const authOptions = {
providers: [
GoogleProvider({
clientId: process.env.GOOGLE_CLIENT_ID,
clientSecret: process.env.GOOGLE_CLIENT_SECRET
})
],
session: {
strategy: "jwt",
},
jwt: {
secret: process.env.JWT_TOKEN
},
adapter: MongooseAdapter(process.env.MONGODB_URI),
}
export default NextAuth(authOptions)
See entire code in my GitHub.
Feel free to ask me any more questions if you feel the need.
Greatly appreciated.
João Textor
Fixed.
callbackUrl should not be like this 'http://127.0.0.1:3000/user/dashboard, but like this: '/user/dashboard'
Simple fix, simple mistake, A LOT OF HEADACHE!

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.

Firebase Cloud Messaging: Internal error encountered

I'm trying to send push notifications via a Firebase Cloud Function, but getting an internal error.
Error: Internal error encountered.
at FirebaseMessagingError.FirebaseError [as constructor] (/srv/node_modules/firebase-admin/lib/utils/error.js:42:28)
at FirebaseMessagingError.PrefixedFirebaseError [as constructor] (/srv/node_modules/firebase-admin/lib/utils/error.js:88:28)
at new FirebaseMessagingError (/srv/node_modules/firebase-admin/lib/utils/error.js:253:16)
at Function.FirebaseMessagingError.fromServerError (/srv/node_modules/firebase-admin/lib/utils/error.js:283:16)
at Object.createFirebaseError (/srv/node_modules/firebase-admin/lib/messaging/messaging-errors.js:34:47)
at FirebaseMessagingRequestHandler.buildSendResponse (/srv/node_modules/firebase-admin/lib/messaging/messaging-api-request.js:119:47)
at /srv/node_modules/firebase-admin/lib/messaging/messaging-api-request.js:94:30
at Array.map (<anonymous>)
at /srv/node_modules/firebase-admin/lib/messaging/messaging-api-request.js:93:30
at <anonymous> errorInfo: [Object], codePrefix: 'messaging'
My function is simple enough:
sendPushNotification.js
const admin = require('firebase-admin');
const messaging = admin.messaging();
module.exports = function(title, deepLink, deviceTokens) {
var message = {
notification: {
title: title
},
data: {
deepLink: deepLink,
},
tokens: deviceTokens
};
console.log(`Sending notification ${title} with Deep Link ${deepLink} to ${deviceTokens.length} devices`);
console.log(deviceTokens);
return messaging.sendMulticast(message).then(response => {
console.log(`Success: ${response.successCount}, failure: ${response.failureCount}`);
if (response.failureCount > 0) {
console.log(response.responses)
}
});
}
The weird thing is that sometimes it does work, but maybe one in 10? The other times I get this less-than-helpful error. The APNs Authentication Key is uploaded in the Firebase Console in the project settings. The App Bundle ID is correct. I'm at a loss for what else could be going on.
(Yes, I am giving the function an array of valid deviceTokens.)
None of the other questions on StackOverflow seem to be related to this internal error, the answers on those questions don't apply here.

What could cause a promise to fail in Nativescript angular2?

I am trying to Http GET from a database , where I do have access and can reproduce the GET result in Postman.
I have created a service in angular2 {N} where I execute this GET but I get an error of :
JS: EXCEPTION: Error: Uncaught (in promise): Response with status: 200 for URL: null
JS: STACKTRACE:
JS: Error: Uncaught (in promise): Response with status: 200 for URL: null
JS: at resolvePromise (/data/data/org.nativescript.ndemo/files/app/tns_modules/zone.js/dist/zone-node.js:496:32)
JS: at resolvePromise (/data/data/org.nativescript.ndemo/files/app/tns_modules/zone.js/dist/zone-node.js:481:18)
JS: at /data/data/org.nativescript.ndemo/files/app/tns_modules/zone.js/dist/zone-node.js:529:18
JS: at ZoneDelegate.invokeTask (/data/data/org.nativescript.ndemo/files/app/tns_modules/zone.js/dist/zone-node.js:314:38)
JS: at Object.NgZoneImpl.inner.inner.fork.onInvokeTask (/data/data/org.nativescript.ndemo/files/app/tns_modules/#angular/core/src/zone/ng_zone_impl.js:37:41)
JS: at ZoneDelegate.invokeTask (/data/data/org.nativescript.ndemo/files/app/tns_modules/zone.js/dist/zone-node.js:313:43)
JS: at Zone.runTask (/data/data/org.nativescript.ndemo/files/app/tns_modules/zone.js/dist/zone-node.js:214:48)
JS: at drainMicroTaskQueue (/data/data/org.nativescript.ndemo/files/app/tns_modules/zone.js/dist/zone-node.js:432:36)
JS: Unhandled Promise rejection: Response with status: 200 for URL: null ; Zone: angular ; Task: Promise.then ; Value: Response with status: 200 for URL: null
JS: Error: Uncaught
(in promise): Response with status: 200 for URL: null
My service :
import { Headers, Http } from '#angular/http';
import 'rxjs/add/operator/toPromise';
export function createNonJsonResponse(http: Http, fullUrl: string): Promise<string>{
return http.get(fullUrl)
.toPromise()
.then(response => response.text())
// .catch(this.handleError);
}
I have logged both the URL given in and the Http and they are fine.
I have no idea why is this happening and google couldn't help me find any solutions whatsoever.
It seems, at least for me, #angular/core Http module is not working as intended. I switched to the nativescript's Http service (https://docs.nativescript.org/cookbook/http) and managed to accomplish what I needed without any problems.
Are you injecting the service somewhere? Add #Injectable() above the export. What if you change how you write the service a little and see if you receive the same response?
#Injectable()
export class createNonJsonResponse {
fullUrl: string = 'http://httpbin.org/get';
constructor(private http: Http) {}
getNonJsonResponse() {
return this.http.get(this.fullUrl)
.toPromise()
.then(response => response.text())
.catch(this.handleErrors);
}
}
Then import it to your component
import {createNonJsonResponse} from "./yourservicename.service"
And finally call it
this.createNonJsonResponse.getNonJsonResponse().then(function (data) {
alert("here");
//console.log(data);
//console.dump(data);
})
This worked for me I was able to hit my alert.

Resources