Copy URL To Clipboard On Npm Run Start

How to copy the start URL and parameters of your application to your clipboard while starting it locally.

David Dal Busco
ITNEXT
Published in
4 min readDec 11, 2020

--

Photo by Gia Oris on Unsplash

I am not sure anyone will ever need the following tricks but, at my client’s place, we have an application which can only be accessed through an URL which contains a dynamic base64 parameter. Needless to say, it makes its local development a bit inconvenient.

In addition, I have to admit, I am not a big fan of CLI’s options which can automatically open browser. Even though I mostly use the Chrome Incognito mode for development purpose, I like to switch often between browsers to try out what I developed.

Finally, I don’t use bookmarks (don’t judge me) and, I often switch between technologies. Therefore, without configuration, every time another port has to be used ( :3333 or :4200 or :8000 or :8100 etc.).

That’s why I had the idea to add a pre-start script to the application which should copy the start URL of the application to my clipboard. Doing so, I can then just select a browser, paste the URI and, I am good to go.

Dependencies

In order to copy or read value to the clipboard from a NodeJS script, I used the library clipboardy which implement such a cross-platform feature.

In addition, I also added chalk and boxen to print out the URL to the console in a stylish way.

You may notice that all these dependencies are open source and developed by the same person, Sindre Sorhus, which definitely deserve a shout-out for this awesome contribution and work 👍.

npm i clipboardy chalk boxen --save-dev

Script

Once the dependencies fetched, I created the pre-start script itself. In this example, I create a file start-url.js at the root of the project.

The script primary generates the url which I am looking to copy in my clipboard. On purpose, I am using an Hello World 👋 string to demonstrate that it is possible to encode complex parameters.

To print out a nice message, I use chalk with colors, in for- and background, and the bold option. I use \n\n to create newlines. It is worth…

--

--