Friday, May 17, 2024
HomeRuby On RailsDeploying and Configuring Lighthouse CI Server

Deploying and Configuring Lighthouse CI Server



Lighthouse on a rocky beach
Photograph by Everaldo Coelho on Unsplash

If you’re into net growth, it’s essential to have come throughout the time period “Lighthouse rating”. It’s a unanimous manner of measuring how properly the web site performs within the wild. To measure the Lighthouse rating, you need to use Lighthouse. Lighthouse is an open-source device that displays and measures your web site’s efficiency, high quality, and correctness.

Lighthouse permits you to to start out rapidly and measure your web site immediately within the browsers. Some groups and corporations run Lighthouse on every change/push. That’s the place Lighthouse CI (LHCI) steps in. LHCI helps you run Lighthouse in steady integration (CI) environments.

After LHCI runs, it might probably add outcomes to a short lived storage offered by Google, or, it might probably add outcomes to a server someplace. Right now, we’re going to learn to deploy after which configure the Lighthouse CI Server in order that we are able to accumulate Lighthouse scores and evaluate them over time.

Conditions

On this weblog submit, we’ll use this weblog – Pragmatic Pineapple to measure its Lighthouse rating. You should utilize your web site if you need, the concept is to an internet site to measure.

For deployment, we’re going to use Railway. Railway is a platform that makes deploying apps simple, by offering a scalable cloud infrastructure. To arrange, you’ll want:

  • A Railway account
  • The Railway CLI put in
  • GitHub repo with a challenge you wish to check with Lighthouse

Step 1 – Initialize Undertaking

First, we’ll create a brand new challenge to host our Lighthouse server code. I named it lighthouse-server and I’ll host it on GitHub.

I created the listing and went inside it:

mkdir lighthouse-server && cd lighthouse-server

The challenge might be easy, with a few important dependencies in bundle.json as seen beneath:

{
  "identify": "lighthouse-server",
  "model": "1.0.0",
  "description": "Nikola's Lighthouse Server",
  "primary": "index.js",
  "scripts": {
    "begin": "node index.js",
    "deploy": "railway up --service=lighthouse-server --environment=manufacturing"
  },
  "key phrases": [],
  "writer": "",
  "license": "ISC",
  "dependencies": {
    "@lhci/server": "^0.12.0",
    "pg": "^8.11.3",
    "pg-hstore": "^2.3.4"
  }
}

Additionally, we’ll want the index.js that may spin up the LHCI server:

"use strict"

const { createServer } = require("@lhci/server")

console.log("Beginning server...")
createServer({
  port: course of.env.PORT,
  storage: {
    storageMethod: "sql",
    sqlDialect: "postgres",
    sqlConnectionSsl: true,
    sqlConnectionUrl: course of.env.DATABASE_URL,
  },
  
}).then(({ port }) => console.log("Listening on port", port))

Or, if you happen to don’t wish to copy textual content as a lot, run these two instructions:

curl https://uncooked.githubusercontent.com/nikolalsvk/lighthouse-server/primary/bundle.json > bundle.json
curl https://uncooked.githubusercontent.com/nikolalsvk/lighthouse-server/primary/index.js > index.js

And we’re good up to now. We now have to deploy the challenge to Railway. Let’s see how to do this.

Step 2 – Deploy to Railway

After we created a brand new listing with bundle.json and index.js, it’s time to deploy it to Railway.

First, we have to run railway login to log in, after which railway init.
Right here’s how that regarded on my machine:

$ railway login
> Open the browser? Sure
Logged in as Nikola ([email protected])

$ railway init
> Crew Private
> Undertaking Identify lighthouse-server
Created challenge lighthouse-server on Private
https://railway.app/challenge/xxxx-xxxx-xxxx-xxxx

Then, we’ll deploy the precise challenge with railway up --detach (the --detach flag is there to ensure we’re not listening to logs of the server).
The command will full fairly rapidly and it’ll set off a deployment on Railway. You may observe the construct logs returned from the command.

$ railway up --detach
Listed
Compressed [====================] 100%
Uploaded
Construct Logs: https://railway.app/challenge/6c35cf2c-d129-4fa4-b224-144a99e96e4b/service/e8f9b583-409a-4109-9604-96e6560bdd25?id=4366fee8-5544-4c0f-a77b-6cb1d969ece9&

The deployment completed in below a minute for me and I acquired this construct log:


Railway Deployment Log

Hm, however the server crashed 🤔. What might be the issue?


Deploy failed

Ah, we don’t have a database for our server. We’ll repair this within the subsequent part.

Step 3 – Add a PostgreSQL Database

So as to add a database for our LHCI server to retailer information, we’ll run railway add.

$ railway add
> Choose plugins to add PostgreSQL
Created PostgreSQL

Select a PostgreSQL by urgent House after which Enter. Now, a PostgreSQL might be added to our private house on Railway.

Now, we’ll join the lighthouse-server service we created, and the PostgreSQL database we added.
Open the Railway and choose the lighthouse-server service and enter the Variables tab like so:


Railway variables

Then, click on the “Add a Variable Reference” hyperlink and you must see a dropdown open like so:


Environment variable dropdown

Choose the DATABASE_URL possibility within the dropdown and also you’ll see the prefilled values:


Add database URL

When you click on “Add”, the redeploy will get scheduled.


Redeploy scheduled

After a few minutes, our deployment is profitable, yay! However how can we view our Lighthouse server?
Nice query, let’s reply it within the subsequent part.

Step 4 – Add a Area on Railway

Now, we have to add a site for our lighthouse-server challenge. Go into the lighthouse-server Settings tab like so:


Settings tab

There, you will notice “Generate area” button. Click on it and you must see the brand new area generated:


Domain generated

Now, if we go to https://lighthouse-server-production-51ca.up.railway.app/app/tasks, we’ll see a welcome message and directions to start out the configuration of the LHCI server:


Welcome to Lighthouse CI

Now, let’s configure the server!

Step 5 – Configure Lighthouse CI Server

Now, we’re going to step away from the lighthouse-server challenge and concentrate on the challenge we wish to measure.
In my case, that’s the weblog you’re presently studying – Pragmatic Pineapple (right here’s the GitHub repo.

I’ll transfer into the basis of the challenge and create a lighthouserc.json file to configure Lighthouse:

{
  "ci": {
    "accumulate": {
      "url": ["http://localhost:9000"],
      "numberOfRuns": 5,
      "startServerCommand": "npm run serve"
    },
    "assert": {
      "preset": "lighthouse:no-pwa"
    },
    "add": {
      "goal": "lhci",
      "serverBaseUrl": "https://lighthouse-server-production-51ca.up.railway.app"
    },
    "headful": false
  }
}

This lighthouserc.json specifies from the place to gather, what to claim, and the place to add Lighthouse outcomes. On this case:

  • We’re accumulating from the http://localhost:9000 after 5 runs of Lighthouse, and we’re operating the weblog server with npm run serve. We’re doing 5 runs to get a greater imply worth, simply in case.
  • We’re asserting towards the lighthouse:no-pwa set of assertions. That could be a set of assertions from Lighthouse containing really helpful thresholds for varied measurements. (I needed to fine-tune the assertions as a result of a few of them have been breaking my construct. I’ll repair them in the future 🤞).
  • And, we’re importing to a customized LHCI server positioned on the URL we beforehand deployed with Railway https://lighthouse-server-production-51ca.up.railway.app.

The vital entry on this JSON file is the serverBaseUrl that tells the place our LHCI server is positioned. Now, we are able to run the LHCI wizard with lhci wizard:

$ lhci wizard

? Which wizard do you wish to run? new-project
? What's the URL of your LHCI server? https://lighthouse-server-production-51ca.up.railway.app
? What would you want to call the challenge? pragmaticpineapple
? The place is the challenge's code hosted? https://github.com/nikolalsvk/weblog
? What department is taken into account the repo's trunk or primary department? grasp
Created challenge pragmaticpineapple (xxxx-xxxx-xxxx-xxxx-xxxx)!
Use construct token xxxx-xxxx-xxxx-xxxx-xxxx to add information.
Use admin token xxxx to handle information. KEEP THIS SECRET!

The wizard configured the distant LHCI server and returned two tokens – construct and admin token. Write down each someplace and preserve them secure.
We’re going to want the construct token later on this weblog submit.

Now, if we go to https://lighthouse-server-production-51ca.up.railway.app, there’s a brand new challenge generated:


Lighthouse new project

If we open the challenge, there’s nothing there.


Empty project

As a result of we didn’t have any Lighthouse runs that despatched the information to our sever, duh!
We’ll repair that shortly.

Step 6 – Recording First Lighthouse Outcome

You’d be tempted to run the Lighthouse CI regionally, however let’s maintain our horses and create a correct solution to do it.

LHCI is supposed to be run, properly, within the CI setting. My weblog is hosted on GitHub, so let’s configure a GitHub Motion that runs the LHCI and uploads it to our freshly deployed LHCI server.

First, let’s create .github and .github/workflows directories.

mkdir .github
mkdir .github/workflows

Then, let’s add .github/workflows/lighthouse-ci.yaml which ought to appear like this:

identify: Construct challenge and run Lighthouse CI

on: [push]

jobs:
  lhci:
    identify: Lighthouse CI
    runs-on: ubuntu-newest
    steps:
      - makes use of: actions/checkout@v3
      - identify: Use Node.js 17.x
        makes use of: actions/setup-node@v3
        with:
          node-version: 17
          cache: "npm"
      - identify: npm set up
        run: |
          npm set up --legacy-peer-deps
      - identify: npm run construct
        run: |
          npm run construct
      - identify: run Lighthouse CI
        run: |
          npm set up -g @lhci/[email protected]
          lhci autorun --upload.githubToken="$LHCI_GITHUB_TOKEN" || echo "LHCI failed!"
        env:
          LHCI_TOKEN: ${{ secrets and techniques.LHCI_TOKEN }}
          LHCI_GITHUB_TOKEN: ${{ secrets and techniques.LHCI_GITHUB_TOKEN }}

This motion runs:

  1. npm set up
  2. npm run construct to construct a manufacturing model of my weblog, and,
  3. lhci autorun that makes use of lighthouserc.json we outlined earlier

One vital factor is that we now have to offer the LHCI_TOKEN to the GitHub Motion. For that, we’ll go into the repository Settings > Secrets and techniques and variables > Actions and click on “New repository secret”. It ought to look one thing like this:


New repository secret

Click on “Add secret” and we’re good to make our first push and set off the LHCI.

Now, each time there’s a push to my weblog repo, a GitHub Motion will run and report a Lighthouse rating to the Lighthouse CI Server we configured on this weblog submit.
Relying on the challenge you’re operating, you might need a unique setup than I’ve, however the idea is comparable:

  1. Put together your challenge (set up deps)
  2. Generate the manufacturing model of the web site
  3. Run lhci autorun on it
  4. Preview outcomes on the customized LHCI server

For instance, right here’s a completed construct on GitHub:


GitHub Actions finished build

The outcomes are reported to the LHCI server right here:


Lighthouse CI server first result

Superior, we now have our LHCI server operating and GitHub Actions reporting on every push to the server our Lighthouse rating. Congrats if you happen to have been following and acquired your first outcome!

What subsequent? I’ve a bonus step for you!

BONUS: Publish a GitHub Commit Standing Verify

We will have LHCI submit a standing verify to our commits as LHCI finishes operating. That’s a good way to see how the Lighthouse run went with out going into the GitHub Motion or opening the LHCI server.Right here’s an instance:


Lighthouse status check

To get began, we’d like a brand new GitHub token with the repo:standing allowed:


Add new GitHub token

Then, we have to add a brand new secret LHCI_GITHUB_TOKEN to repository’s Settings > Settings > Secrets and techniques and variables > Actions. Discover how we now have two secrets and techniques:


Two GitHub secrets

And, lastly, let’s inform lhci our token by modifying the .github/workflows/lighthouse-ci.yaml:

identify: Construct challenge and run Lighthouse CI

on: [push]

jobs:
  lhci:
    identify: Lighthouse CI
    runs-on: ubuntu-newest
    steps:
      // different steps

      - identify: run Lighthouse CI
        run: |
          npm set up -g @lhci/[email protected]
          lhci autorun --upload.githubToken="$LHCI_GITHUB_TOKEN" || echo "LHCI failed!"
        env:
          LHCI_TOKEN: ${{ secrets and techniques.LHCI_TOKEN }}
          LHCI_GITHUB_TOKEN: ${{ secrets and techniques.LHCI_GITHUB_TOKEN }}

We added the --upload.githubToken="$LHCI_GITHUB_TOKEN" possibility and within the env we made positive LHCI_GITHUB_TOKEN is ready correctly from the repository’s secrets and techniques.

Now, you’ll get a brand new commit standing verify each time a Lighthouse runs for that commit, yay!


Lighthouse status check

Please observe, there’s an official Lighthouse GitHub app that may do the same factor for you.

Let’s join lighthouse-server to Railway mechanically each time we push to the repo’s primary department. This might be easy since all we have to do is to attach the GitHub repo to a lighthouse-server Railway challenge of their UI.

In case you haven’t already, now is an effective time to publish your LHCI configuration we labored on in step 1. You too can use the one I’ve over at lighthouse-server repo on GitHub.

Inside lighthouse-server Settings tab in Railway, there’s a bit for connecting a GitHub repository like so:


Railway connect a repo

As soon as clicked, we’ll be taken to GitHub to arrange the GitHub Railway app. Right here, you may permit entry to all repos or simply those you need. I chosen the lighthouse-server GitHub repo and put in the app.


Railway GitHub config

As soon as put in, return to the Railway lighthouse-server Settings tab and click on “Join Repo”. Now, you must see the repos you allowed Railway to entry. I chosen the lighthouse-server GitHub repo and now every little thing is related.


Railway and GitHub repo connected

Now, each time I push to the repo – Railway will deploy the change, yay!


Railway deploy on change

Summing Up

And that’s it! The Lighthouse CI server is now deployed and configured on Railway along with a database to retailer your challenge’s runs.
Every commit will run Lighthouse, submit outcomes, and guarantee your websites are quick and accessible.

You will discover all of the code for the lighthouse-server on GitHub right here.
And the PR the place I added the Lighthouse workflow to my weblog.

Now, all I (and doubtless you) have to do is to ramp up that Lighthouse rating and avoid the rocks ⛰ 🔦 🚢.

Thanks for studying, and I’ll catch you within the subsequent one.

Cheers.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments