Joshua's Docs - Glitch Cheat Sheet and Advanced Documentation

Welcome to my Glitch Cheat Sheet and quick reference guide! I made this because I had some trouble tracking down this information, and wanted to make it easier for others to find. Let me know if you find something amiss!

Table of Contents

Click to View ToC

External Resources

Click to View Some Recommended Resources
What & Link Type
Official: Live System Status Page Ops Status Page
Official: Help Center
Β Β  - New Ticket
Β Β  - Login / Existing Tickets
Help Center
Official: Support Forums Forums
Official: "What kind of apps can I make with Glitch?" Help Page
Official: Technical Restrictions for Glitch Projects Help Page
Flavio Copes: "Introduction to Glitch for Node.JS"
- Great high-level overview of some of Glitch's best features for NodeJS development
Intro Guide
MozVR / MrEd: Lessons from Hacking Glitch
- Covers an interesting use-case for Glitch; as a host for a distributed editor / learning demo.
Blog Post
"The HyperDev Tech Stack"
- Covers some of the history of Glitch, as well as info about how it runs (or at least, how it was built initially)
Blog Post
"Running Datasette on Glitch"
- Covers an advanced use-case for Glitch, as well as the use of glitch.json
Blog Post
"Web App Deploy to Glitch.com"
- Interesting use-case: automated .zip deployments that are unpacked on Glitch for static hosting
Project Post

Badges and Public Info

For embedding badges, see my note here

Hosting Configuration

You might be wondering "How does Glitch know what to do with the code I've uploaded? How does it pick what files to serve for the live view?"

The answer is not very well documented, but I'll do my best to do so below:

Glitch Configuration Defaults

If you don't make any tweaks to the advanced configuration settings (see below sections for details), then Glitch will attempt to detect the type of project you are using, and execute the appropriate install and startup actions. It does this with its "watcher" program; you can poke around the guts of it in /opt/watcher (or maybe don't? I'm not sure how they feel about this...)

The main hosting defaults are:

Here is what Glitch does with each of these types of environments, to host your app:

App Type On Install On Start
Static Nothing! Starts live webserver, hosting current directory (.).

I think they are using a combination of ws for websockets, and local-web-server (aka lws) for hosting.
NodeJS Detect Node version, install node_modules dependencies.
- If Node version changes between builds, it will flush and rebuild dependencies folder
- Technically it uses pnpm instead of npm for dependency management
- Detects Node version
- If there, runs scripts.prestart first from package.json
- Runs scripts.start from package.json
Python Runs pip install --user -r requirements.txt As far as I can tell, it basically runs Python in a loop, keeping it up, with PYTHONUNBUFFERED=true
Generated Static See NodeJS entry - should work similarly See Static entry - should work the same, although this project type will serve /build.

While using the Glitch editor, the build script will get called after edits are made.
Custom Tries to run install entry from glitch.json Tries to run start entry from glitch.json

Node version is first detected from engines->node in package.json (reference), and if not present, seems to go off suggested version installed in the Glitch docker image.

Project Type: Generated Static

In 2021, Glitch introduced a new project type: Generated Static.

What does this new project type get you?

  • In the past the way that Glitch worked with projects that produced static build output (e.g. React, Svelte, Vue, Eleventy, etc.) is that it would call your start script entry, which usually built and then served the site via a NodeJS process instead of via the Glitch static HTML serving function. This usually meant that those types of projects, even though they were generating (typically) small static files, would take a long time to launch and used up lots of Glitch resource time, even if no source files had changed.
  • This new project type is a crossover between the NodeJS project type and the free static project type
    • While using the Glitch editor / IDE and making edits, your build script will get called after changes have been made to generate new static output. I'm not 100% sure, but it is likely that start is used for live previewing, but only while in the IDE.
    • When someone visits your Glitch, instead of running start, like a normal NodeJS project, instead the Glitch system treats your project as a static project type, and serves whatever is in the /build folder.
    • This ultimately is a huge improvement for projects that produce static output
      • You only incur resource usage while working on your app within the IDE, since that uses more CPU to produce the build output
      • When the app is not being edited, the previous build output is cached (at /build), and served to users via the free static hosting option - no resource usage incurred

You can enable this new project type by cloning one of the new starters, or by setting a special value in you root package.json:

{
	// ...
	"glitch": {
		"projectType": "generated_static"
	},
	// ...
}

Your project doesn't even have to be built with a framework that matches an existing starter - the real requirements are that you have a build script entry that produced static output at /build, and the above key-pair in your package.json file.

A more technical announcement of this project type can be found here.

glitch.json

The glitch.json file is an advanced control mechanism built into Glitch that I had to do some digging to find. It shares similarity with watch.json (and can contain its configuration as a subset), but additionally contains overriding controls for how installs and starts are handled.

The schema of glitch.json looks like this:

{
	// Command executed upon initial use, or core files change
	"install": "./my-installer.sh",
	// Run every time
	"start": "./my-runner.sh",
	/**
	* This section can be extracted to `watch.json` (alternatively)
	* @SEE `watch.json` section below for docs
	*/
	"watch": {
		"install": {
			"include": ["^package\\.json$", "^\\.env$"]
		},
		"restart": {
			"exclude": ["^public/", "^dist/"],
			"include": ["\\.js$", "\\.ts$", "\\.json", "\\.tsconfig"]
		},
		"throttle": 100
	}
}

WARNING: commands that execute via glitch.json have a much smaller subset of environmental values / binary PATHs exposed than those executed via package.json -> scripts. See troubleshooting section for details.

watch.json

The watch.json file can be used to control what triggers an app "reload" in Glitch, and how. The schema should look something like this:

// Instead of using glob patterns, Glitch uses regexp strings (NOT regexp literals)
type RegExpStr = string;

type WatchJson = {
	// These patterns are for files to ignore entirely
	ignore?: RegExpStr[],
	// These trigger hard reloads (kill, install, then start)
	install: {
		include?: RegExpStr[],
		exclude?: RegExpStr[]
	},
	// These trigger soft reloads (kill, and then start command)
	restart: {
		include?: RegExpStr[],
		exclude?: RegExpStr[]
	},
	// This applies a hard limit to how often the Glitch watcher can reload - a value of 5000 would be once per every 5 seconds
	throttle: number
}

And here is the example from the watch-json Glitch demo:

{
	"install": {
		"include": ["^package\\.json$", "^\\.env$"]
	},
	"restart": {
		"exclude": ["^public/", "^dist/"],
		"include": ["\\.js$", "\\.coffee$", "\\.json"]
	},
	"throttle": 100
}

Sources:

Git Integration

Glitch App as Git Repo

Each Glitch app is actually automatically a git repo! You can access it both inside Glitch (via the built-in console) and outside Glitch (via standard git origin settings).

If you want to access the repo outside the Glitch IDE, you can find the .git URL by going to Tools -> Import and Export -> Your project's Git URL: -> Copy. You can then use it as an origin in your local git client, and for writing / merging, follow the guide here.

Github Sync

In addition to manually using Glitch's git integration to push and pull code, you can also have Glitch automatically fetch an existing repo from Github and import the code directly into Glitch, all via a simple popup. Just use Tools -> Import and Export -> Import from Github -> {paste in repo URL} -> OK

NOTE: Importing from Github via the UI is a one-way and one-time operation - it does not automatically keep your Glitch in sync with Github. If you are looking for an approach to keeping them in sync, check out: "Automating my Deploys from Github to Glitch". Or glitch-github-sync.

File Storage

Most file storage on Glitch works as expected, with a few caveats.

  • Binary assets are hidden by default from the IDE / editor / file navigator
  • /assets is a special folder on Glitch; it does not represent a true directory under home, but rather a virtual directory that stores a map of assets to CDN file URLs
    • You can determine your assets CDN URL by reading in the file .glitch-assets, which contains line-separate JSON objects
  • When you create / edit files via the CLI, you should call refresh to have their changes reflected in the IDE

.glitch-assets JSON

As mentioned above, there is a special file that Glitch auto-creates in the root of your project: .glitch-assets. This is a plain-text file, that contains line-delimited entries for files that are stored in the virtual /assets directory. Glitch uses a CDN for these files, so each entry in the file is a mapping of the filename to a CDN URL.

The schema looks something like this (subject to change):

Deleted File:

{
	// Unique ID
	"uuid": "Oc4vw2CgZU0Ze3xn",
	// true, of course
	"deleted": true
}

Existing File:

{
	"name": "test.zip",
	"uuid": "P3seg1KqutANMJty",
	"date": "2020-07-18T22:42:06.024Z",
	"url": "https://cdn.glitch.com/7f58909a-dc20-425f-8445-97f933eb77a6 %2Ftest.zip",
	"type": "application/x-zip-compressed",
	"size": 119,
	"thumbnail": "https://cdn.glitch.com/7f58909a-dc20-425f-8445-97f933eb77a6%2Fthumbnails%2Ftest.zip",
	"thumbnailWidth":210,
	"thumbnailHeight":210
}

Note: Notice that uuid does not seem to be a standard GUID / UUID. Instead, seems to be 16 characters, alpha-numeric and mixed case.

date looks to be in ISO-8601 format

Package Management

How to add a package

The preferred way is to use the editor's built-in GUI - see official help page.

However, you can also add packages the normal dev way; by using the pnpm install {package} command, or by hand-editing package.json and then calling pnpm install.

NPM install commands are supported, but you'll need to switch from PNPM to NPM.

Switching between PNPM and NPM

⚠ WARNING: Switching to NPM will often increase the amount of disk space that your project uses (under App Status -> Disk), since PNPM is heavily optimized for storage.

To switch between NPM and PNPM, you need to open the Terminal, and then use one of the following commands:

  • To switch from PNPM to NPM
    • enable-npm
  • To switch from NPM to PNPM
    • enable-pnpm

For those curious, those commands essentially flip a flag in a stored config file, wipe node_modules, and then call the refresh command to rebuild the project.

Advanced Tricks and Tips

  • If you have a scripts.prestart entry in your package.json, Glitch will run that command before running scripts.start!
  • You can store and retrieve binary assets on Glitch, but they might not be visible in the editor / file navigator
  • How to tell if your code is executing on Glitch?
    • The easiest way to tell if you code is executing on glitch is by checking for system environmental variables that are unique to Glitch (server-side), or by checking the domain name / path (front-end).
    • I've built a tiny NPM package that can be used: detect-is-on-glitch
  • The Glitch environment actually ships with a lot of built-in tools!!!
    • Every Glitch app is really running in its own micro-instance of Linux (with Docker), with a surprising amount of built-in packages pre-installed!
    • For example, out of the box, you can get: git, pip (Python), perl, php, mongodb, and many more!
  • You can execute shell scripts within Glitch!
    • These are callable from the standard spots, as well as install and watch via glitch.json config.
  • Use cd ~ to get back to your apps project root if you get lost in the console
  • You can copy files from the special assets area to your source code; just grab the CDN URL and then use wget in the terminal to download it where you want it in your source code folder.

Troubleshooting

Error using glitch.json: /opt/watcher/app-types/custom/install.sh: line __: yarn: command not found (or npm: command not found) (or /usr/bin/env: β€˜node’: No such file or directory)

  • This is a strange one; if you are using package.json, the appropriate tools should already be installed. Even if you swap out your commands to use pnpm, you will still probably still get the /usr/bin/env: β€˜node’: No such file or directory error.
  • I believe I finally tracked this down; the problem is that there are some Glitch configuration / setup scripts that run before all other actions (install, start, watch), and one of the things that they do is reset the PATH variable:
    • It uses export PATH=${USER_PATH}, where USER_PATH is a much slimmer version of PATH, without Node, Yarn, Pip, etc.
  • The easiest solution is to avoid executing lots of commands from both the console and watch.json - instead, sticking to scripts entries in package.json is the safest
    • The reason why package.scripts.start does not suffer from the same issue and instead works fine, even when calling node, is because there are separate setup shell scripts for default configs that add the correct Node version to the PATH
    • My advice here is also in line with some of the official responses
  • Technically, you could probably reformulate the correct PATH string and then set the variable, but this might be more effort than it is worth, plus, could break if Glitch changes their Linux / Docker image setup

As a desperate workaround, you can manually call the program you need (yarn, pnpm, node) by:

  1. Using which {program_cmd} to find the stored location
    • E.g. which node -> /opt/nvm/versions/node/v8/bin/node
  2. Using the FULL path of the program you found in step 1, to execute your desired command
    • E.g. change node server.js to /opt/nvm/versions/node/v8/bin/node server.js

Sample script:

#!/usr/bin/env bash

# `node` is not exposed in PATH, so use full path
/opt/nvm/versions/node/v8/bin/node server.js

❓ Error using glitch.json: my-script.sh: command not found

To execute shell scripts with glitch.json, make sure two main rules are followed:

  • Use correct paths. If shell script is in root of project, path should look like ./my-script.sh, NOT my-script.sh
  • Use correct permissions. Try chmod +x my-script.sh from the Glitch terminal

❓ Error using glitch.json: /opt/watcher/app-types/custom/start.sh: ./my-script.sh: /usr/bin/env: bad interpreter: Text file busy

Likely because there is essentially a "lock" on the file, from recently editing it in the Glitch editor, or something like that.

Easy fix: run refresh from the Glitch terminal.


❓ "I've updated / created / deleted a file from the console, but the IDE / file explorer doesn't reflect my changes!"

Try running refresh from the console; this should sync changes across.


πŸ› I can't add a package via the CLI with pnpm add {package}! It stalls out CLI says "store server is running".

Try adding the dependency directly instead of through the CLI, by hand-editing package.json, and then calling pnpm install.

For example, if you are trying to install a hosted tarball, you can add "my-package": "https://{public_host}/my-package.1.0.0.tgz". After you have added the dependency, then call pnpm install.


πŸ› With default Create-React-App projects (CRA), my app never successfully starts, and I keep getting failed to start application on [...] in the live view.

It looks like this issue is caused by CRA's reliance on TTY, and how Glitch has configured their Docker container(s). I've outlined a fix in this blog post / writeup.


πŸ› Trying to use pnpm install {local_tarball_path.tgz} I get the error: ERROR  ENOENT: no such file or directory, open '{local_tarball_path.tgz}'

I opened up a support thread in their forums, and the TLDR from that is that installing local tarballs with PNPM is basically unsupported on Glitch.

To clarify, although PNPM supports adding local packages via packed tarballs, this fails on Glitch due to how Glitch has configured the shared PNPM global store. Most likely this error is caused by the fact that the store is on a separate volume, and PNPM can't read across to where /app is mounted when it tries to add the tarball.

There are two main workarounds:

  • Switch project to NPM using enable-npm, then install tarball with the appropriate NPM command (npm install {local_tarball_path.tgz}). Be warned that using NPM instead of PNPM on Glitch will cause your project to use more disk space.
    • Or...
  • Keep using PNPM, but use pnpm install {REMOTE_URL_tarball.tgz}, or in package.json, "package-name": "{REMOTE_URL_tarball.tgz}"

πŸ’‘ TIP: If you choose the second option, using a remote URL, you can use the assets part of Glitch to upload the *.tgz file and get a hosted URL you can then use!


πŸ› My packages keep reinstalling every time my Glitch project wakes up, even though no code has changed!

This is basically a known issue with Glitch, and there are more than one support threads about the topic. AFAIK, this should not happen unless:

  • package.json is edited
  • shrinkwrap.yaml is changd
  • Node version is changed
  • Checksum file is removed / altered
  • You have a custom install command that is doing it
  • The Glitch project container is reset?

The last bullet point is what I think the culprit might often be, especially if you are 100% sure you haven't changed anything. Unfortunately, I cannot find this documented anywhere, but some forum posts seem to suggest that beyond the auto-sleep functionality (currently triggered after 5 minutes of inactivity), there is also a hard-reset every twelve hours or so, regardless of activity. Again, I can't find docs on this so I'm not sure what a "hard reset" entails (beyond clearing /tmp), but if it removes the special checksum file that is meant to track dependencies, then that would explain why packages reinstall after a container restart, regardless of if actual code has changed.

Markdown Source Last Updated:
Wed Jun 02 2021 02:04:21 GMT+0000 (Coordinated Universal Time)
Markdown Source Created:
Thu Jul 09 2020 21:53:03 GMT+0000 (Coordinated Universal Time)
Β© 2024 Joshua Tzucker, Built with Gatsby
Feedback