Error with URL in NextJS and I can't find the problem - reactjs

I have an error that appear in both development and production mode, however, this error only crash the website in production.
I have this error returned:
unhandledRejection: TypeError: Only absolute URLs are supported
at getNodeRequestOptions (D:\FIV\nextjs-fiv-4\node_modules\node-fetch\lib\index.js:1305:9)
at D:\FIV\nextjs-fiv-4\node_modules\node-fetch\lib\index.js:1410:19
at new Promise (<anonymous>)
at Function.fetch [as default] (D:\FIV\nextjs-fiv-4\node_modules\node-fetch\lib\index.js:1407:9)
at fetchWithAgent (D:\FIV\nextjs-fiv-4\node_modules\next\dist\server\node-polyfill-fetch.js:38:39)
at _callee$ (D:\FIV\nextjs-fiv-4\node_modules\swell-js\dist\api.js:191:20)
at tryCatch (D:\FIV\nextjs-fiv-4\node_modules\regenerator-runtime\runtime.js:63:40)
at Generator.invoke [as _invoke] (D:\FIV\nextjs-fiv-4\node_modules\regenerator-runtime\runtime.js:294:22)
at Generator.next (D:\FIV\nextjs-fiv-4\node_modules\regenerator-runtime\runtime.js:119:21)
at asyncGeneratorStep (D:\FIV\nextjs-fiv-4\node_modules\swell-js\node_modules\#babel\runtime\helpers\asyncToGenerator.js:3:24)
And I know that this is the element below causing this error, when I remove it, the error disappears. But I do not understand how to correct it, or what's wrong when checking the network tab. In the network tab I see that this is calling http://localhost:3000/null/api/cart instead of https://my-store.swell.store/api/cart which is weird because on other page this URL is called correctly and I use an .env file to set my environment variables.
//Render Stripe Card Element
var customCardElement = swell.payment.createElements({
card: {
elementId: '#card-element', // default: #card-element
options: {
style: {
base: {
fontWeight: 500,
fontSize: "16px"
},
},
},
onChange: event => {
//setDisabled(event.empty);
if(event.error){
//setError(event.error.message);
}
}
}
});

Client side NextJS variables are only available if prefixed with NEXT_PUBLIC_ because well... they're public

Related

"Server Error ReferenceError: self is not defined" in use the powerbi-client-react with typescript project

I tried to use the lib powerbi-client-react in my project written in typescript, but I get the following error when I try to run it:
my component code:
import { PowerBIEmbed } from 'powerbi-client-react';
import { models } from 'powerbi-client';
// aditional declarete from use "window" in my getEmbeddedComponent
declare global {
interface Window { report: any; }
}
export default function PbiEmbeddedDashboard() {
return (
<div className="App">
<PowerBIEmbed
embedConfig={{
type: 'report', // Supported types: report, dashboard, tile, visual and qna
id: '<Report Id>', // the information has been filled in correctly in the project
embedUrl: '<Embed Url>', // the information has been filled in correctly in the project
accessToken: '<Access Token>', // the information has been filled in correctly in the project
tokenType: models.TokenType.Embed, // i also tried to use the models.TokenType.Aad but the error was the same
settings: {
panes: {
filters: {
expanded: false,
visible: false
}
},
background: models.BackgroundType.Transparent,
}
}}
eventHandlers={
new Map([
['loaded', function () { console.log('Report loaded'); }],
['rendered', function () { console.log('Report rendered'); }],
['error', function (event) { console.log(event.detail); }]
])
}
cssClassName={"report-style-class"}
getEmbeddedComponent={(embeddedReport) => {
window.report = embeddedReport;
}}
/>
</div>
)
};
This is return error:
Server Error
ReferenceError: self is not defined
This error happened while generating the page. Any console logs will be displayed in the terminal window.
Call Stack
Object.<anonymous>
file:///home/myProject/sistema-web-myProject/be-front/node_modules/powerbi-client-react/dist/powerbi-client-react.js (1:452)
Module._compile
internal/modules/cjs/loader.js (1085:14)
Object.Module._extensions..js
internal/modules/cjs/loader.js (1114:10)
module.load
internal/modules/cjs/loader.js (950:32)
Function.Module._load
internal/modules/cjs/loader.js (790:12)
module.require
internal/modules/cjs/loader.js (974:19)
require
internal/modules/cjs/helpers.js (101:18)
Object.powerbi-client-react
file:///home/myProject/sistema-web-myProject/be-front/.next/server/pages/dashboards/pbi.js (52:18)
__webpack_require__
file:///home/myProject/sistema-web-myProject/be-front/.next/server/webpack-runtime.js (33:42)
eval
webpack-internal:///./src/util/pbiEmbedded/pbi_getAccessToken.tsx (9:78)
What sounds strange to me is that I used pretty much the same code in another project written in javascript and everything seems to work fine.
Could you help me solve this problem and understand what is happening?
i also tried to use the models.TokenType.Aad but the error was the same
I didn't find anything related to this

Simple Peer on data stream throws process not defined error

I am trying to open a data channel using simple peer. I send the signal using Firebase and am able to get the on connect function to fire.
const [thisPeer, setThisPeer] = useState();
const [connectionStatus, setConnectionStatus] = useState(false);
// in a function
var thisPeerT = new Peer({
initiator: false,
config: {
iceServers: iceServers,
},
});
// signaling code
thisPeerT.on("connect", function (data) {
console.log("onconnect");
console.log(data);
setConnectionStatus(true);
});
setThisPeer(thisPeerT);
In the on connect, I set a state hook that triggers a use effect where I create my on data.
useEffect(
function () {
console.log("here");
console.log(roomID);
console.log(thisPeer);
console.log(connectionStatus);
if (roomID && thisPeer && connectionStatus) {
console.log("here2");
thisPeer.on("data", function (data) {
console.log(data);
});
}
},
[roomID, thisPeer, connectionStatus]
);
However, I get the following error when I try to use thisPeer.on("data"...
here
XXYDCgqle4XvZDZ6gm6
Peer {_readableState: ReadableState, readable: true, _events: {…}, _eventsCount: 4, _maxListeners: undefined, …}
true
here2
Uncaught ReferenceError: process is not defined
at resume (_stream_readable.js:905:1)
at Peer.Readable.resume (_stream_readable.js:895:1)
at Peer.Readable.on (_stream_readable.js:813:1)
at ConnectionContext.js:142:1
at invokePassiveEffectCreate (react-dom.development.js:23487:1)
at HTMLUnknownElement.callCallback (react-dom.development.js:3945:1)
at Object.invokeGuardedCallbackDev (react-dom.development.js:3994:1)
at invokeGuardedCallback (react-dom.development.js:4056:1)
at flushPassiveEffectsImpl (react-dom.development.js:23574:1)
at unstable_runWithPriority (scheduler.development.js:468:1)
I have tried placing the on data at various places throughout my code, and regardless of the position, it seems this error occurs. If I call peer.send() on the other peer, it also gives a process is not defined error on the peer that received the data. Does anyone know how I can resolve the error or where I should open the data channel?
I got the same issue but I can do a workaround by using CDN script
<script src="https://cdnjs.cloudflare.com/ajax/libs/simple-peer/9.11.1/simplepeer.min.js"></script>
And here is a code example of how to call it in React
var peer1 = new window.SimplePeer({ initiator: true })

I get "Invalid Plugin Options" Error with Prismic Plugin in Gatsby

I'm using CodeSandbox to make a Gatsby app and I'm trying to use Prismic for the backend. I set it up nicely, I'm sure, and I installed gatsby-source-prismic to my project. However, when I add it to my config file and restart the project, it throws an error saying "Invalid Plugin Options". This is what's in my plugin file:
{
resolve: `gatsby-source-prismic`,
options: {
repositoryName: `firstprism`,
accessToken: `XXX`
},
},
Here's the stack:
ERROR
gatsby-source-prismic - invalid plugin options
ERROR
Expected a value of type record<string,object> forschemas but received undefined.
Error:
index.cjs:650 new StructError
[sandbox]/[superstruct]/lib/index.cjs:650:19
index.cjs:707 Function.Struct.assert
[sandbox]/[superstruct]/lib/index.cjs:707:13
index.cjs:679 Struct
[sandbox]/[superstruct]/lib/index.cjs:679:19
gatsby-node.js:74 validatePluginOptions
[sandbox]/[gatsby-source-prismic]/dist/gatsby-node.js:74:50
gatsby-node.js:1042
[sandbox]/[gatsby-source-prismic]/dist/gatsby-node.js:1042:25
Generator.next
gatsby-node.js:52
[sandbox]/[gatsby-source-prismic]/dist/gatsby-node.js:52:71
new Promise
gatsby-node.js:48 __awaiter
[sandbox]/[gatsby-source-prismic]/dist/gatsby-node.js:48:12
gatsby-node.js:1029 Object.sourceNodes
[sandbox]/[gatsby-source-prismic]/dist/gatsby-node.js:1029:55
api-runner-node.js:256 runAPI
[sandbox]/[gatsby]/dist/utils/api-runner-node.js:256:37
api-runner-node.js:375 resolve
[sandbox]/[gatsby]/dist/utils/api-runner-node.js:375:15
debuggability.js:384 Promise._execute
[sandbox]/[bluebird]/js/release/debuggability.js:384:9
promise.js:518 Promise._resolveFromExecutor
[sandbox]/[bluebird]/js/release/promise.js:518:18
promise.js:103 new Promise
[sandbox]/[bluebird]/js/release/promise.js:103:10
api-runner-node.js:374 Promise.mapSeries.plugin
[sandbox]/[gatsby]/dist/utils/api-runner-node.js:374:12
I just ran into this issue. It appears it is now required to provide JSON schemas, as described here in the docs : https://github.com/angeloashmore/gatsby-source-prismic#providing-json-schemas
edit: please also refer to https://github.com/angeloashmore/gatsby-source-prismic/blob/master/docs/migrating-from-v2-to-v3.md
It's like this
options: {
repositoryName: 'your-repository-name',
accessToken: `${process.env.API_KEY}`,
linkResolver: ({ node, key, value }) => post => `/${post.uid}`,
schemas: {
page: require("./src/schemas/page.json"),
},
},
instead of this now
options: {
repositoryName: `your-repository-name`,
accessToken: `${process.env.API_KEY}`,
linkResolver: ({ node, key, value }) => post => `/${post.uid}`,
page: require("./src/schemas/page.json"),
},

Nodejs - FindOneAndUpdate method works but makes my website crash (using mongo) on events.js

I want to delete an array index with an ID that I get from front-end. My code works fine and the elements are deleted, however the website crashes and I have to restart npm or check mongo's atlas to check the results. I'm really in the dark here.
Here's the error:
events.js:167
throw er; // Unhandled 'error' event
^
ReferenceError: errors is not defined
at User.findOneAndUpdate (C:\repos\InventoryApp\routes\index.js:52:17)
at C:\repos\InventoryApp\node_modules\mongoose\lib\model.js:4851:16
at process.nextTick (C:\repos\InventoryApp\node_modules\mongoose\lib\query.js:2776:28)
at process._tickCallback (internal/process/next_tick.js:61:11)
Emitted 'error' event at:
at C:\repos\InventoryApp\node_modules\mongoose\lib\model.js:4853:13
at process.nextTick (C:\repos\InventoryApp\node_modules\mongoose\lib\query.js:2776:28)
at process._tickCallback (internal/process/next_tick.js:61:11)
[nodemon] app crashed - waiting for file changes before starting...
//all variables are set and I have done a push method with the same variables
User.findOneAndUpdate(
{ email : useremail },
{ $pull: { products: {
_id : mongoose.Types.ObjectId(id)
} } },
(err) => {
if (err) console.log('found errors');
req.flash('success_msg', 'New record');
})
I found out that mongoose.Types.ObjectId(id) was causing this issue.
By doing _id : id I mananged to make it work.

In-Context Checkout: Uncaught SecurityError: Blocked a frame with origin: checkout.js:4734 throws error

I'm implementing PayPal's In-Context Checkout and am using Advanced In-Context JavaScript settings (https://developer.paypal.com/docs/classic/express-checkout/in-context/javascript_advanced_settings)
My app is a React app. So I can't use PP API as they suggest it, that is just throw a code between <script> ... </script> tags somewhere in the page under their buttons. My React components have state and data that I need to send to server within PP function calls. So I placed PP code in componentDidMount method. And for some reason PP throws this error:
checkout.js:4734 Uncaught SecurityError: Blocked a frame with origin "http://example.com:3000" from accessing a frame with origin "https://www.sandbox.paypal.com". The frame requesting access has a protocol of "http", the frame being accessed has a protocol of "https". Protocols must match.
(anonymous function) # checkout.js:4734
checkout.js:4515 GET http://www.paypalobjects.com/api/oneTouch.html net::ERR_EMPTY_RESPONSE
Here is the code:
componentDidMount() {
window.paypalCheckoutReady = function() {
paypal.checkout.setup(config[NODE_ENV].ppMerchantID, {
locale: 'en_US',
environment: 'sandbox',
buttons: [
{
container: 'checkoutBtnContainer',
type: 'checkout',
color: 'gold',
size: 'medium',
shape: 'pill',
click: (ev)=>{
paypal.checkout.initXO();
$.post('/checkout', {
checkoutData: this.props.checkoutData,
})
.done(res => {
paypal.checkout.startFlow(res.link);
})
.fail(err => {
paypal.checkout.closeFlow();
});
}
}
],
});
};
},
I know about cross-origin policy. I don't understand why it is the case here. Why the code works fine if I throw it on the page between <script> ... </script> tags, but PP throws an error if I use it in my React component. What is the cause of that? Is it React fault or PayPal's?
UPD: No, below is not a solution for the problem. Occasionally Paypal's checkout.js script throws the error.
However, it solves this issue
Apparently,
1) there was no this:
window.paypalCheckoutReady = function() {
// wrong this is here
}
I changed to:
window.paypalCheckoutReady = () => {
// correct this is here now
}
I don't like .bind(this).
2) I removed <form /> tag and set plain <div> instead:
// before
<form id="checkoutBtnContainer" method="post" action="/checkout"></form>
// after
<div id="checkoutBtnContainer"></div>
I don't know why and how, but all works fine now.

Resources