Running A Gatsby Site Locally Using Netlify CLI
- Published on
- -2 min read
As I have been delving deeper into adding more functionality to my Gatsby site within the Netlify eco-system, it only seemed natural that I should install the CLI to make development faster and easier to test builds locally before releasing them to my Netlify site. There have been times when I have added a new feature to my site to only find it breaks during the build process eating up those precious build minutes.
One thing that I found a miss from the Netlify CLI documentation were the steps to running a site locally, in my case a Gatsby JS site. The first time I ran the netlify dev
command, I was greeted by an empty browser window served under http://localhost:8888
.
There were a couple of steps I was missing to test my site within a locally run Netlify setup.
1) Build Site
The Gatsby site needs to be compiled so all HTML, CSS and JavaScript files are generated as physical files on your machine. When the following command is run, all files will be generated within the /public
folder of your project:
gatsby build
The build
command creates a version of your site with production-ready optimisations by packaging up your site’s configurations, data and creating all the static HTML pages. Unlike the serve
command, you cannot view the site once the build has been completed. Only files are generated, which is exactly what we need.
2) Run Netlify Dev Command From Build Directory
Now that we have a built version of the site generated locally within the /public
folder, we need to run the Netlify Dev command against this directory by running the following:
netlify dev -dir public
As you can see, the dir
flag is used to run our site from where the compiled site files reside. I originally had a misconception in thinking the Netlify Dev command would build my Gatsby site as well, when in fact it does not.
Conclusion
If you have a site hosted by Netlify, using the CLI should is highly recommended as it provides you that extra step in ensuring any updates made can be tested prior to deployment. My site uses Netlify features such as redirects and plugins, which I now can test locally instead of going down the previously inefficient route of:
- Deploying changes to Netlify.
- Waiting for the build process to complete.
- Test changes within the preview site.
- If all is good, publish the site. If not, resolve error and deploy again.
This endless cycle of development hell is now avoided thanks to the safety net the Netlify CLI provides.
Further Reading
Before you go...
If you've found this post helpful, you can buy me a coffee. It's certainly not necessary but much appreciated!
Leave A Comment
If you have any questions or suggestions, feel free to leave a comment. Your comment will not only help others, but also myself.