← ALL POSTS

Using Next.js to create a browser extension (Chrome & Firefox)

2021-01-27

If you’ve been following my journey lately you’ll have seen I’m all in on Next.js. I find it so flexible and easy to use for 99% of use cases, it’s my go-to for new projects and I’ve even migrated some old ones to it.

My latest venture has been PrivaNote (https://privanote.xyz). It’s a simple, offline first and end-to-end encrypted note taking application. Behind the scenes it stores data in IndexedDB (gracefully falls back to LocalStorage if that’s unavailable thanks to the LocalForage library) and if you enable the end-to-end encrypted sync it leverages Portabella (https://portabella.io) for storage. A separate post will be coming soon with more details on how I wrote this but it’s also open source if you want to take a look at the code.

While writing PrivaNote I had the idea to make it my default “new tab” page so I can easily jott down ideas whenever I have them. What I mean practically is, pressing CMD + N on my keyboard (an operation I already do all the time) should open up PrivaNote instead of an empty tab.

I figured this would be pretty easy to implement, browser extensions for Chrome and addons for Firefox already support this “newtab” override functionality, but actually packaging up the Next.js application was a little trickier.

Here’s my script in its entirety for you to copy if you want to give it a go yourself:

rm -rf .next/ out/;
rm extension.zip;

yarn next build;
yarn next export;

cp manifest.json ./out;

mv ./out/_next ./out/next
cd ./out && grep -rli '_next' * | xargs -I@ sed -i '' 's/_next/next/g' @;

zip -r -FS ../my-extension.zip *;

I won’t break down every line for you, the first few are just building your Next.js project as usual. You’ll also want to make sure you’re bundling the out/ directory, not the .next/ directory, meaning you have to export your project.

What’s really interesting is the next instead of _next stuff. Basically Chrome won’t let browser extensions import JavaScript files that start with an underscore. So trying to add a <script src="/_next/static/chunk.js" /> tag won’t work out of the box, we just need to replace _next with next (or any string you prefer). The sed command shown here works on Mac OS but you might have to fiddle with it if you’re using a different OS.

I hope you have some luck with creating extensions or addons for Next.js apps. The application in question (privanote.xyz) has been released as a Chrome extension and a Firefox addon so check it out!