Using crypto.randomInt() in React - node.js

I am trying to use crypto.randomInt() Nodejs API in a project bootstrapped with create-react-app that uses Webpack 5. I have tried multiple options like this so far:
// webpack.config.js
module.exports = {
resolve: {
fallback: { crypto: require.resolve('crypto-browserify') },
}
};
And then, npm i crypto-browserify as recommended by the error message.
// Returns Uncaught TypeError: randomInt is not a function
const { randomInt } = import('crypto');
console.log(randomInt(4));
From some threads, I tried:
// package.json
...
"browser": {
"crypto": false
}
...
Still, no luck. I tried import {randomInt} from 'crypto-browserify'. This didn't work either.
What should I do to make this work?

Related

sveltekit environment variables are not working with turborepo and vercel deployment

Hi guys I have the following turborepo configuration
{
"$schema": "https://turbo.build/schema.json",
"pipeline": {
"build": {
"dependsOn": ["^build"],
"outputs": [".svelte-kit/**", ".vercel/**"],
"env": ["PUBLIC_SUPABASE_URL", "PUBLIC_SUPABASE_ANON_KEY"]
},
"lint": {},
"dev": {
"cache": false,
"persistent": true
}
}
}
It's a simple project with 2 sveltekit websites, admin and client, both websites have a supabase instance and the client is defined like this
import { createClient } from '#supabase/auth-helpers-sveltekit';
import { PUBLIC_SUPABASE_ANON_KEY, PUBLIC_SUPABASE_URL } from '$env/static/public';
export const client = createClient(PUBLIC_SUPABASE_URL, PUBLIC_SUPABASE_ANON_KEY);
in development locally it works perfectly but in production it fails with a different error for each website, for admin the vite config is this
import { sveltekit } from '#sveltejs/kit/vite';
import type { UserConfig } from 'vite';
const config: UserConfig = {
plugins: [sveltekit()],
optimizeDeps: {
exclude: ['flowbite-svelte']
},
define: {
'process.env': process.env
}
};
export default config;
and the error is this:
admin:build: throw new Error('supabaseUrl is required.');
admin:build: ^
admin:build:
admin:build: Error: supabaseUrl is required.
admin:build: at new SupabaseClient (/vercel/path0/node_modules/.pnpm/#supabase+supabase-js#2.4.1/node_modules/#supabase/supabase-js/dist/main/SupabaseClient.js:55:19)
Which just means it is not seeing the variables
for client the vite config is this
import { sveltekit } from '#sveltejs/kit/vite';
/** #type {import('vite').UserConfig} */
const config = {
plugins: [sveltekit()]
};
export default config;
and the error in vercel is this:
client:build: "PUBLIC_SUPABASE_URL" is not exported by "$env/static/public", imported by "src/lib/db.ts".
client:build: file: /vercel/path0/apps/client/src/lib/db.ts:2:35
client:build: 1: import { createClient } from '#supabase/auth-helpers-sveltekit';
client:build: 2: import { PUBLIC_SUPABASE_ANON_KEY, PUBLIC_SUPABASE_URL } from '$env/static/public';
client:build: ^
client:build: 3: export const client = createClient(PUBLIC_SUPABASE_URL, PUBLIC_SUPABASE_ANON_KEY);
client:build: error during build:
client:build: RollupError: "PUBLIC_SUPABASE_URL" is not exported by "$env/static/public", imported by "src/lib/db.ts".
client:build: at error (file:///vercel/path0/node_modules/.pnpm/rollup#3.7.3/node_modules/rollup/dist/es/shared/rollup.js:2001:30)
in both cases the issue is that the environment variables are not being loaded in both I don't understand why, I made sure the variables are configured correctly on vercel

Migrating cypress test from old version to latest version throws error

I am trying to migrate my test from Cypress 8.7.0 version to Cypress 10.10.0 version. Installed the latest version and did the below settings, but getting below error.
Using below versions:
Cypress 10.10.0,
"#badeball/cypress-cucumber-preprocessor": "^11.4.0",
node v18.4.0,
#bahmutov/cypress-esbuild-preprocessor": "^2.1.5"
Expected to find a global registry (this usually means you are trying to define steps or hooks in support/e2e.js, which is not supported) (this might be a bug, please report at https://github.com/badeball/cypress-cucumber-preprocessor)
Because this error occurred during a before each hook we are skipping all of the remaining tests.
I have added the error handling in e2e.js file and support/index.js file but still could not resolve this issue. I have .env file which has the environment variable in my root location. Could someone please advise on this issue ?
//Detail error log:
Because this error occurred during a `before each` hook we are skipping all of the remaining tests.
at fail (tests?p=tests/cypress/e2e/login/loginBase.feature:964:15)
at assert (tests?p=tests/cypress/e2e/login/loginBase.feature:971:9)
at assertAndReturn (tests?p=tests/cypress/e2e/login/loginBase.feature:975:9)
at getRegistry (tests?
Cypress version : v10.10.0
//tests/cypress/e2e/login/login.feature
#regression
#login
Feature: Login to base url
Scenario: Login to base url
Given I go to base url
//step defintion:
tests/cypress/stepDefinitions/login.cy.js
import { Given, When, Then, Before, After, And } from "#badeball/cypress-cucumber-preprocessor";
When('I go to base url', () => {
cy.visit(Cypress.config().baseUrl);
})
// tests/cypress/support/index.js file
// Import commands.js using ES2015 syntax:
import './commands'
Cypress.on('uncaught:exception', (err, runnable) => {
// returning false here prevents Cypress from
// failing the test
return false
});
//tests/cypress/support/e2e.js
// Import commands.js using ES2015 syntax:
import './commands'
Cypress.on('uncaught:exception', (err, runnable) => {
// returning false here prevents Cypress from
// failing the test
return false
})
//.cypress-cucumber-preprocessorrc.json // add this file in project root location
{
"stepDefinitions": [
"[filepath].{js,ts}",
"tests/cypress/stepDefinitions/**/*.{js,ts}"
]
}
// cypress.config.js
const { defineConfig } = require('cypress')
const createBundler = require("#bahmutov/cypress-esbuild-preprocessor");
const addCucumberPreprocessorPlugin = require("#badeball/cypress-cucumber-preprocessor")
const createEsbuildPlugin = require("#badeball/cypress-cucumber-preprocessor/esbuild").createEsbuildPlugin;
const dotenvPlugin = require('cypress-dotenv');
async function setupNodeEvents(on, config) {
await addCucumberPreprocessorPlugin.addCucumberPreprocessorPlugin(on, config);
on(
"file:preprocessor",
createBundler({
plugins: [createEsbuildPlugin(config)],
})
);
//webpack config goes here if required
config = dotenvPlugin(config)
return config;
}
module.exports = defineConfig({
e2e: {
baseUrl: 'https://bookmain.co',
apiUrl: 'https://bookmain.co/api/books/',
specPattern: "tests/cypress/e2e/**/*.feature",
supportFile: false,
setupNodeEvents
},
component: {
devServer: {
framework: "next",
bundler: "webpack",
},
},
});
// package.json
"cypress-cucumber-preprocessor": {
"nonGlobalStepDefinitions": true,
"stepDefinitions": "tests/cypress/stepDefinitions/**/*.{js,ts}",
"cucumberJson": {
"generate": true,
"outputFolder": "tests/cypress/cucumber-json",
"filePrefix": "",
"fileSuffix": ".cucumber"
}
},
In cypress.config.js add the following:
const {dotenvPlugin} = require('cypress-dotenv');
module.exports = (on, config) => {
config = dotenvPlugin(config)
return config
}
This will resolve the issue.

Can't resolve 'http' in '/tmp/build_6c942c65/src' in Heroku: App works locally

My app which works locally cannot be pushed to heroku because of this error message:
Module not found: Error: Can't resolve 'http' in '/tmp/build_6c942c65/src'
Steps I have tried:
Downgrading react scripts to 4.0.2
Trying install http-browserify https-browserify and updating next.config.js to the below:
module.exports = {
webpack: (config, { buildId, dev, isServer, defaultLoaders, webpack }) => {
config.resolve.alias.https = "https-browserify";
config.resolve.alias.http = "http-browserify";
return config;
},
};
Installing node-polyfill-webpack-plugin, creating a webpack.config.js and adding
const NodePolyfillPlugin = require('node-polyfill-webpack-plugin');
module.exports = {
// Other rules...
plugins: [
new NodePolyfillPlugin()
]
};
Also
putting this in webpack.config.js
module.exports = {
target: "node",
}
Can anyone help.
App directory looks like this:
Can anyone help?
Thanks

Webpack using perf_hooks for node/browser module

I'm making a module that I would like to be available in the browser and Node. It relies on performance, which is giving me trouble with Webpack and the perf_hooks module in Node. No matter what I do I can only get it where it works in one or the other, but not both.
Below are most of the things I've tried. My question is, how do I configure Webpack to require perf_hooks in node, but use the built in performance global when in the browser?
Here is my base Webpack config:
const path = require('path');
module.exports = {
entry: './src/UpdateLoop.js',
mode: 'development',
output: {
library: 'UpdateLoop',
libraryTarget: 'umd',
path: path.resolve(__dirname, 'dist'),
filename: 'updateloop.js',
globalObject: 'this',
},
};
Code thats giving me trouble:
const { performance } = require('perf_hooks');
This errors in webpack with:
Field 'browser' doesn't contain a valid alias configuration
resolve as module
C:\Users\joe.jankowiak\projects\update-loop\src\node_modules doesn't exist or is not a directory
I've seen suggestions for 'fs' to do the following:
// configuration.node has an unknown property 'perf_hooks'
node: {
perf_hooks: false,
},
// configuration has an unknown property 'browser'.
browser: {
perf_hooks: false,
},
I then saw people recommending using 'resolve':
// Compiles, but complains performance doesn't exist in node or browser.
resolve: {
fallback: {
perf_hooks: false,
}
},
// Works in browser but doesn't work in node. Node complains about using performance before its defined:
performance = performance || require('perf_hooks').performance;
// Doesn't work in either
const performance = performance || require('perf_hooks').performance;
// Trying to check if its node, but with resolve its making perf_hooks null in node
if(typeof __webpack_require__ === 'function') {
global.performance = require('perf_hooks').performance;
}
I ended up doing this out of laziness because I still don't quite understand how to use NodeJS functions with Webpack:
function portableMsecTimer () {
if (process.hrtime) {
return Number(process.hrtime.bigint()) / 1e6;
} else {
return window.performance.now();
}
}

Bundle error using webpack for Electron application `Cannot resolve module 'electron'`

I am trying to create an Electron application with React. I use Webpack to compile the React JSX syntax, but when I try to compile with webpack command, I got this error:
ERROR in ./app.jsx
Module not found: Error: Cannot resolve module 'electron' in /Users/masterT/Downloads/gist
# ./app.jsx 6:18-37
Here is the application code.
I am doing something wrong?
A very simple solution :
const remote = window.require('electron').remote;
webpack will ignore this require
Webpack tries to resolve electron module with the installed node_modules. But the electron module is resolved in Electron itself at runtime. So, you have to exclude particular module from webpack bundling like this:
webpack.config.js:
module.exports = {
entry: './app.jsx',
output: {
path: './built',
filename: 'app.js'
},
target: 'atom',
module: {
loaders: [
{
loader: 'babel',
test: /\.jsx$/,
query: {
presets: ['es2015', 'react']
}
}
]
},
externals: [
(function () {
var IGNORES = [
'electron'
];
return function (context, request, callback) {
if (IGNORES.indexOf(request) >= 0) {
return callback(null, "require('" + request + "')");
}
return callback();
};
})()
]
};
You can set target: 'electron' in your webpack config and then you don't have to exclude electron in externals.
From webpack documentation:
"electron" Compile for usage in Electron – supports require-ing Electron-specific modules.
I tried most of the above examples, but none of them seemed to work for me.
I then installed Electron using npm and then used yarn build
It worked and I got my production build.
npm i electron
Also, webpack.config.js:
const nodeExternals = require('webpack-node-externals')
module.exports = {
...
externals: [ nodeExternals(), 'react', 'electron' ],
...
}
Your package.json has 'electron-prebuilt' but you require 'electron' in your code. Have you tried require-ing 'electron-prebuild'?

Resources