
Deploy React app on Gitlab Pages
- 2 minsGitLab Pages Deployment
This is a quick guide on deploying a React app on GitLab Pages. The following files are required to have it working properly. An example of this app can be see here
.gitlab-ci.yml
A file named “.gitlab-ci.yml” should be added to the repository root directory. This is the bread and butter of the continuous integration/continuous devliery part of Gitlab Pages. The file should have the environment and scripts to build and deploy the React app for you. Once its been run, it should move the build folder contents into /public directory for page deployment. However, I have caught myself running into errors with trailing slashes and back slashes when copying directory content.
More specifically this line here
- cp -r $CI_PROJECT_DIR/build/* public
Previously I had this setup
- cp -r $CI_PROJECT_DIR/build public
which would copy the entire build dir into the public dir leaving me with this.
$CI_PROJECT_DIR/public/build
The builds would succeed but gitlab pages would show the new website as a white page. After realizing that I only needed the contents in the build dir I tried a few steps that copied all the content and the removed the build dir all together. That too fails. So to finally resolve this and have a working react app showing on Gitlab pages my .gitlab-ci.yml file looks like this.
image: node:20
cache:
paths:
- node_modules/
stages:
- build
- deploy
build:
stage: build
script:
- rm -rf node_modules package-lock.json
- npm install
- ls -la public/ # Debug: Verify public/ directory contents
- npm run build
- ls -la build/ # Debug: Verify build/ directory contents
#- mv build public
artifacts:
paths:
- public/
expire_in: 1 hour
only:
- main
pages:
stage: deploy
script:
# If creating a syymlink doesn’ŧ work for any reason replace the line ln -s $CI_PROJECT_DIR/portfolio/public public with cp -r $CI_PROJECT_DIR/portfolio/public .
- cp -r $CI_PROJECT_DIR/build/* public
- echo "Deploying to GitLab Pages" # move build contents to new /public directory
- export
artifacts:
paths:
- public # only allow paths in project root directory for some reason
environment:
name: production
url: https://dave.meralus.com
dependencies:
- build
only:
- main
package.json
The package.json file requires the following line to be added as well.
"homepage": "https://custom-url.com/"
Setting the homepage URL the react app is important because it sets the app’s routing and asset paths and makes sure they are configured relative to the project’s URL. Without this, the app may fail to load resources properly, leading to broken links, a non-functional site, or a blank white page.
Hopes this helps someone out there. More importantly I hope it helps myself when I look back and read this 6 months from now lol.