How to run lighthouse for the homepage after login from puppeteer - reactjs

I added two npm "#lhci/cli" and puppeteer.After that I added two config file
lighthouserc.js : config details are:
module.exports = {
ci: {
upload: {
target: 'temporary-public-storage'
},
collect: {
puppeteerScript: 'puppeteer-script.js',
chromePath: puppeteer.executablePath(),
url: ["https://myWebsite.com/abc"],
headful: true,
numberOfRuns: 1,
disableStorageReset: true,
setting: {
disableStorageReset: true
},
puppeteerLaunchOptions: {
slowMo: 20,
headless: false,
disableStorageReset: true
}
},
assert: {
assertions: {
'categories:performance': ['warn', { minScore: 1 }],
'categories:accessibility': ['error', { minScore: 0.5 }]
}
}
}
};
puppeteer-script.js
module.exports = async (browser, context) => {
await page.setDefaultNavigationTimeout(90000);
await page.goto(context.url);
await page.type('input[type=text]', 'abc');
await page.type('input[type=email]', 'abc#abc.com');
await page.type('input[type=password]', 'abc#100');
await page.click('[type="button"]');
await page.waitForNavigation({ waitUntil: "networkidle2" })
await page.close();
};
and in package.json I added script command as :
"test:lighthouse": "lhci autorun --collect.settings.chromeFlags='--no-sandbox'"
Now Login is working fine but I want to run the lighthouse for the url that I specified in lighthouserc.js (https://myWebsite.com/abc).
But after login it is trying to access the url and again login screen is coming and the lighthouse is measuring performance for the login page.
Is it possible to run lighthouse on url I specified in the config.Please assist me.
https://myWebsite.com/abc is my reactjs application

I do not have complete information on the workflow of your site but as mentioned in the configuration guide puppeteer script is run for each url mentioned in the lhci config file.
And after puppeteer script is ran, lighthouse will open URL. Now if your site is opening login page again, that its an issue with your app or configuration most likely. Either your app is not setting cookie correctly or login process is failing somehow, you will need to check that.
Also, as puppeteer script will be running for every url in the config, its good idea to not re-login if you already logged in once, check out this issue on Github.

Related

Service worker PWA + Amplify Deployment issues

We are currently hosting a react app with amplify and have recently enabled the service worker via workbox to become PWA compatible. Our amplify app uses Cloudflare + S3 to serve our built react app. After enabling the service worker, when pushing new code and triggering a build, we noticed that if a user was on the site and refreshed their app, it would get a 404 error
https://ourwebsite.com/static/js/main.3j3k232.chunk.js 404 not found
This error would persist until the user would do a hard refresh on the browser. Our service worker previously was set to createHandlerBoundToURL() but we opted for NetworkFirst() instead because we were curious about solving the N+1 update problem. This was after the createHandlerBoundToURL() version of the service worker was deployed already.
import { clientsClaim } from 'workbox-core';
import { ExpirationPlugin } from 'workbox-expiration';
import { precacheAndRoute, createHandlerBoundToURL } from 'workbox-precaching';
import { registerRoute } from 'workbox-routing';
import { NetworkFirst, NetworkOnly, StaleWhileRevalidate } from 'workbox-strategies';
declare const self: ServiceWorkerGlobalScope;
clientsClaim();
// Precache all of the assets generated by your build process.
// Their URLs are injected into the manifest variable below.
// This variable must be present somewhere in your service worker file,
// even if you decide not to use precaching. See https://cra.link/PWA
precacheAndRoute(self.__WB_MANIFEST);
// Set up App Shell-style routing, so that all navigation requests
// are fulfilled with your index.html shell. Learn more at
// https://developers.google.com/web/fundamentals/architecture/app-shell
const fileExtensionRegexp = new RegExp('/[^/?]+\\.[^/]+$');
registerRoute(
// Return false to exempt requests from being fulfilled by index.html.
({ request, url }: { request: Request; url: URL }) => {
// If this isn't a navigation, skip.
if (request.mode !== 'navigate') {
return false;
}
// If this is a URL that starts with /_, skip.
if (url.pathname.startsWith('/_')) {
return false;
}
// If this looks like a URL for a resource, because it contains
// a file extension, skip.
if (url.pathname.match(fileExtensionRegexp)) {
return false;
}
// Return true to signal that we want to use the handler.
return true;
},
// createHandlerBoundToURL(process.env.PUBLIC_URL + '/index.html') // initially had this enabled
new NetworkFirst()
);
// An example runtime caching route for requests that aren't handled by the
// precache, in this case same-origin .png requests like those from in public/
registerRoute(
// Add in any other file extensions or routing criteria as needed.
({ url }) =>
url.origin === self.location.origin && url.pathname.endsWith('.png'),
// Customize this strategy as needed, e.g., by changing to CacheFirst.
new StaleWhileRevalidate({
cacheName: 'images',
plugins: [
// Ensure that once this runtime cache reaches a maximum size the
// least-recently used images are removed.
new ExpirationPlugin({ maxEntries: 50 }),
],
})
);
// This allows the web app to trigger skipWaiting via
// registration.waiting.postMessage({type: 'SKIP_WAITING'})
self.addEventListener('message', (event) => {
if (event.data && event.data.type === 'SKIP_WAITING') {
self.skipWaiting();
}
});
To reproduce this, we would only have to push new code and trigger a build, after it was completed the user would just need to refresh and they could be met with a 404 blank screen. We are using this PWA in a TWA android application.
Any help would be appreciated! We suspect it could also be an issue with CloudFront CDN as we have read that CDNs can cause issues with service workers and their caches.

Why is my amplify environment variable appearing for just a moment then disappearing again [duplicate]

So i'm using the Contentful API to get some content from my account and display it in my Next.Js app (i'm using next 9.4.4). Very basic here. Now to protect my credentials, i'd like to use environment variables (i've never used it before and i'm new to all of this so i'm a little bit losted).
I'm using the following to create the Contentful Client in my index.js file :
const client = require('contentful').createClient({
space: 'MYSPACEID',
accessToken: 'MYACCESSTOKEN',
});
MYSPACEID and MYACCESSTOKEN are hardcoded, so i'd like to put them in an .env file to protect it and don't make it public when deploying on Vercel.
I've created a .env file and filled it like this :
CONTENTFUL_SPACE_ID=MYSPACEID
CONTENTFUL_ACCESS_TOKEN=MYACCESSTOKEN
Of course, MYACCESSTOKEN and MYSPACEID contains the right keys.
Then in my index.js file, i do the following :
const client = require('contentful').createClient({
space: `${process.env.CONTENTFUL_SPACE_ID}`,
accessToken: `${process.env.CONTENTFUL_ACCESS_TOKEN}`,
});
But it doesn't work when i use yarn dev, i get the following console error :
{
sys: { type: 'Error', id: 'NotFound' },
message: 'The resource could not be found.',
requestId: 'c7340a45-a1ef-4171-93de-c606672b65c3'
}
Here is my Homepage and how i retrieve the content from Contentful and pass them as props to my components :
const client = require('contentful').createClient({
space: 'MYSPACEID',
accessToken: 'MYACCESSTOKEN',
});
function Home(props) {
return (
<div>
<Head>
<title>My Page</title>
<link rel="icon" href="/favicon.ico" />
</Head>
<main id="page-home">
<Modal />
<NavTwo />
<Hero item={props.myEntries[0]} />
<Footer />
</main>
</div>
);
}
Home.getInitialProps = async () => {
const myEntries = await client.getEntries({
content_type: 'mycontenttype',
});
return {
myEntries: myEntries.items
};
};
export default Home;
Where do you think my error comes from?
Researching about my issue, i've also tried to understand how api works in next.js as i've read it could be better to create api requests in pages/api/ but i don't understand how to get the content and then pass the response into my pages components like i did here..
Any help would be much appreciated!
EDIT :
So i've fixed this by adding my env variables to my next.config.js like so :
const withSass = require('#zeit/next-sass');
module.exports = withSass({
webpack(config, options) {
const rules = [
{
test: /\.scss$/,
use: [{ loader: 'sass-loader' }],
},
];
return {
...config,
module: { ...config.module, rules: [...config.module.rules, ...rules] },
};
},
env: {
CONTENTFUL_SPACE_ID: process.env.CONTENTFUL_SPACE_ID,
CONTENTFUL_ACCESS_TOKEN: process.env.CONTENTFUL_ACCESS_TOKEN,
},
});
if you are using latest version of nextJs ( above 9 )
then follow these steps :
Create a .env.local file in the root of the project.
Add the prefix NEXT_PUBLIC_ to all of your environment variables.
eg: NEXT_PUBLIC_SOMETHING=12345
use them in any JS file like with prefix process.env
eg: process.env.NEXT_PUBLIC_SOMETHING
You can't make this kind of request from the client-side without exposing your API credentials. You have to have a backend.
You can use Next.js /pages/api to make a request to Contentful and then pass it to your front-end.
Just create a .env file, add variables and reference it in your API route as following:
process.env.CONTENTFUL_SPACE_ID
Since Next.js 9.4 you don't need next.config.js for that.
By adding the variables to next.config.js you've exposed the secrets to client-side. Anyone can see these secrets.
New Environment Variables Support
Create a Next.js App with Contentful and Deploy It with Vercel
Blog example using Next.js and Contentful
I recomended to update at nextjs 9.4 and up, use this example:
.env.local
NEXT_PUBLIC_SECRET_KEY=i7z7GeS38r10orTRr1i
and in any part of your code you could use:
.js
const SECRET_KEY = process.env.NEXT_PUBLIC_SECRET_KEY
note that it must be the same name of the key "NEXT_PUBLIC_ SECRET_KEY" and not only "SECRET_KEY"
and when you run it make sure that in the log says
$ next dev
Loaded env from E:\awesome-project\client\.env.local
ready - started server on http://localhost:3000
...
To read more about environment variables see this link
Don't put sensitive things in next.config.js however in my case I have some env variables that aren't sensitive at all and I need them Server Side as well as Client side and then you can do:
// .env file:
VARIABLE_X=XYZ
// next.config.js
module.exports = {
env: {
VARIABLE_X: process.env.VARIABLE_X,
},
}
You have to make a simple change in next.config.js
const nextConfig = {
reactStrictMode: true,
env:{
MYACCESSTOKEN : process.env.MYACCESSTOKEN,
MYSPACEID: process.env.MYSPACEID,
}
}
module.exports = nextConfig
change it like this
Refer docs
You need to add a next.config.js file in your project. Define env variables in that file and those will be available inside your app.
npm i --save dotenv-webpack#2.0.0 // version 3.0.0 has a bug
create .env.development.local file in the root. and add your environment variables here:
AUTH0_COOKIE_SECRET=eirhg32urrroeroro9344u9832789327432894###
NODE_ENV=development
AUTH0_NAMESPACE=https:ilmrerino.auth0.com
create next.config.js in the root of your app.
const Dotenv = require("dotenv-webpack");
module.exports = {
webpack: (config) => {
config.resolve.alias["#"] = path.resolve(__dirname);
config.plugins.push(new Dotenv({ silent: true }));
return config;
},
};
However those env variables are gonna be accessed by the server. if you want to use any of the env variables you have to add one more configuration.
module.exports = {
webpack: (config) => {
config.resolve.alias["#"] = path.resolve(__dirname);
config.plugins.push(new Dotenv({ silent: true }));
return config;
},
env: {
AUTH0_NAMESPACE: process.env.AUTH0_NAMESPACE,
},
};
For me, the solution was simply restarting the local server :)
Gave me a headache and then fixed it on accident.
It did not occur to me that env variables are loaded when the server is starting.

Create react app PWA manifest.json not being cached

I'm building a React app using create-react-app and I used the following command to make it from the beginning a PWA.
npx create-react-app my-app --template cra-template-pwa
After building my app, going to the browser developer tools, and look into the cache, I noticed all my images and files are cached but not my manifest.json. I can see my manifest.json being in the app since I can look at it in the dev tools and I can install the app on my computer. The problem comes when I go offline, the manifest.json is not found because it's not cached.
How can I cache my manifest.json?
Why my manifest.json isn't cached as default?
This is the error I see in my console when I serve the app offline:
GET http://localhost:5000/manifest.json net::ERR_INTERNET_DISCONNECTED
200
Service Worker generated by CRA;
import { clientsClaim } from 'workbox-core';
import { ExpirationPlugin } from 'workbox-expiration';
import { precacheAndRoute, createHandlerBoundToURL } from 'workbox-precaching';
import { registerRoute } from 'workbox-routing';
import { StaleWhileRevalidate } from 'workbox-strategies';
clientsClaim();
// Precache all of the assets generated by your build process.
// Their URLs are injected into the manifest variable below.
// This variable must be present somewhere in your service worker file,
// even if you decide not to use precaching. See https://cra.link/PWA
precacheAndRoute(self.__WB_MANIFEST);
// Set up App Shell-style routing, so that all navigation requests
// are fulfilled with your index.html shell. Learn more at
// https://developers.google.com/web/fundamentals/architecture/app-shell
const fileExtensionRegexp = new RegExp('/[^/?]+\\.[^/]+$');
registerRoute(
// Return false to exempt requests from being fulfilled by index.html.
({ request, url }) => {
// If this isn't a navigation, skip.
if (request.mode !== 'navigate') {
return false;
} // If this is a URL that starts with /_, skip.
if (url.pathname.startsWith('/_')) {
return false;
} // If this looks like a URL for a resource, because it contains // a file extension, skip.
if (url.pathname.match(fileExtensionRegexp)) {
return false;
} // Return true to signal that we want to use the handler.
return true;
},
createHandlerBoundToURL(process.env.PUBLIC_URL + '/index.html')
);
// An example runtime caching route for requests that aren't handled by the
// precache, in this case same-origin .png requests like those from in public/
registerRoute(
// Add in any other file extensions or routing criteria as needed.
({ url }) => url.origin === self.location.origin && url.pathname.endsWith('.png'), // Customize this strategy as needed, e.g., by changing to CacheFirst.
new StaleWhileRevalidate({
cacheName: 'images',
plugins: [
// Ensure that once this runtime cache reaches a maximum size the
// least-recently used images are removed.
new ExpirationPlugin({ maxEntries: 50 }),
],
})
);
// This allows the web app to trigger skipWaiting via
// registration.waiting.postMessage({type: 'SKIP_WAITING'})
self.addEventListener('message', (event) => {
if (event.data && event.data.type === 'SKIP_WAITING') {
self.skipWaiting();
}
});```

Cypress.io and Cucumber.io testing integration, Step implementation missing for:

Integration of Cypress and Cucumber seem to go well, however when tests are executed I get the following error:
Step implementation missing for: I open login page
cypress.json
{
"video": false,
"baseUrl": "http://localhost:8080",
"testFiles": "**/*.feature",
"cypress-cucumber-preprocessor": {
"nonGlobalStepDefinitions": true
}
}
./cypress/integration/login.feature
Feature: Login Feature
I want to login
#focus
Scenario: Navigate to Login
Given I open login page
Then I see Login
./cypress/integration/Login/login.js
import { Given, Then } from 'cypress-cucumber-preprocessor/steps';
Given( 'I open login page', () => cy.visit( '/Login' ) );
Then( 'Login page should be shown', () => cy.url().should( 'include', '/Login' ) );
Your cypress-cucumber-preprocessor config should go in package.json, not in cypress.json.
Also, I believe the step implementation folder name must match the feature file name. So you should rename your step implementation folder to login instead of Login (./cypress/integration/login/login.js)
See doc here
Add step_defintions in your package.json with custom path
"cypress-cucumber-preprocessor": {
"step_definitions": "cypress/integration/features/step_definitions/**/"
}
While I do not think this answer is ideal, I managed to get things working by removing "cypress-cucumber-preprocessor" from cypress.json and moving sub directories from the "cypress/integration" directory to "cypress/support/step_definitions"

Websockets, truffle, ganache and react setup issues connection not open on send()

Sometimes I refresh, and it works. Sometimes it just doesn't work.
I tried changing ganache GUI settings to use port 8545 which I read is the WebSockets port but it still won't connect. ws:127.0.0.1 won't work and neither will http://
This is my truffle config file. The rest of the code is large and won't help much.
// See <http://truffleframework.com/docs/advanced/configuration>
// #truffle/hdwallet-provider
// var HDWalletProvider = require("truffle-hdwallet-provider");
const path = require("path");
var HDWalletProvider = require("#truffle/hdwallet-provider");
module.exports = {
// See <http://truffleframework.com/docs/advanced/configuration>
// to customize your Truffle configuration!
// contracts_directory: "./allMyStuff/someStuff/theContractFolder",
contracts_build_directory: path.join(__dirname, "/_truffle/build/contracts"),
// migrations_directory: "./allMyStuff/someStuff/theMigrationsFolder",
networks: {
ganache: {
host: "127.0.0.1",
port: 7545,
//port: 8545,
network_id: 5777,
//network_id: "*", // Match any network id,
websockets: false, // websockets true breaks TODO: connection not open on send()
// wss
},
},
};
This is some of my code on the actual screen in question.
const options = {
web3: {
block: false,
fallback: {
type: 'ws',
//url: 'ws://127.0.0.1:8546',
url: 'http://127.0.0.1:7545',
},
},
contracts: [MyStringStore],
// polls: {
// accounts: IntervalInMilliseconds,
// },
events: {},
};
I don't understand why sometimes it works and I can see drizzle state and sometimes I can't. React native and web3 is very new to me.
I get errors like this:
00:06 Contract MyStringStore not found on network ID: undefined
Error fetching accounts:
00:06 connection not open
I am having real difficulty setting up drizzle as well. One thing I see is that your
url: 'http://127.0.0.1:7545',
For some reason Drizzle only works with 'ws' as the prefix for such a URL. I am trying to follow this guide by people who got it working.
I think websocket is only available in the command line version.
Try install and use ganache-cli instead of the gui version.

Resources