DEV Community

Cover image for Static Web Apps CLI and Node.js 18: could not connect to API
John Reilly
John Reilly

Posted on • Edited on • Originally published at johnnyreilly.com

Static Web Apps CLI and Node.js 18: could not connect to API

I make use of Azure Static Web Apps a lot. I recently upgraded to Node.js 18 and found that the Static Web Apps CLI no longer worked when trying to run locally; the API would not connect when running swa start:

[swa] ❌ Could not connect to "http://localhost:7071/". Is the server up and running?

This post shares a workaround.

title image reading "Static Web Apps CLI and Node.js 18: could not connect to API" with the Static Web Apps CLI and Node.js logos

The issue

My own setup is a Vite front end and a Function App back end. I have a package.json in the folder of the front end app with the following scripts:

"dev": "vite",
"start": "swa start http://localhost:5173 --run \"npm run dev\" --api-location ../FunctionApp"
Enter fullscreen mode Exit fullscreen mode

I could see both front end and back end starting up in the console, but inevitably the SWA CLI would report:

[swa] ❌ Could not connect to "http://localhost:7071/". Is the server up and running?

It turned out this came down to the version of Node.js I was using. I was using Node.js 18. Or rather it was due to an issue with a dependency of the Static Web Apps CLI; the wait-on library which waits for endpoints to become available. With Node.js 18 this is broken. It's not clear a fix is imminent.

The workaround

Various workarounds are suggested in this GitHub issue. I shared my own there, and I'm sharing it here too. (Mostly for me, I'll lay money I need this again and again.)

In the root of my project I installed concurrently:

npm i concurrently
Enter fullscreen mode Exit fullscreen mode

Then, again in the root of my project I added the following scripts:

"debug": "concurrently -n \"staticwebapp,functionapp\" -c \"bgBlue.bold,bgMagenta.bold\" \"npm run debug:staticwebapp\" \"npm run debug:functionapp\"",
"debug:staticwebapp": "cd src/StaticWebApp && npm run debug",
"debug:functionapp": "cd src/FunctionApp && func start",
Enter fullscreen mode Exit fullscreen mode

What's happening here is that I'm running the Static Web Apps CLI and the Function App CLI in separate processes, and running them concurrently when we run npm run debug. You'll note that the debug:staticwebapp script is running another debug script with the Static Web Apps CLI in the src/StaticWebApp folder:

"debug": "swa start http://localhost:5173 --run \"npm run dev\" --api-location http://127.0.0.1:7071",
Enter fullscreen mode Exit fullscreen mode

The --api-location flag is pointing to the endpoint the Function App is surfaced at. This is the key to the workaround.

Summary

This takes us back to having a setup that will work with Node.js 18. Hopefully this is only needed for a short while, but it's good to have a workaround in the meantime.

Top comments (0)