WiFi + Fetch
Connect to a WiFi network and make an HTTP request to a JSON API.
Hardware
- Any ESP32 board with WiFi
- USB-C cable
- A WiFi network with internet access
Setup
Set your WiFi credentials as environment variables:
npx mikro env set WIFI_SSID YourNetworkName
npx mikro env set WIFI_PASSPHRASE --secret
Code
import {fetch} from 'mikrojs/fetch'
import {memoryUsage} from 'mikrojs/sys'
import wifi from 'mikrojs/wifi'
// Country must be set before using WiFi
wifi.country = 'NO'
const {WIFI_SSID: ssid, WIFI_PASSPHRASE: passphrase} = import.meta.env
// Connect to WiFi
console.log(`Connecting to ${ssid}...`)
const connectResult = await wifi.connect(ssid, passphrase)
if (!connectResult.ok) {
console.error('WiFi connect failed:', connectResult.error.name)
} else {
console.log('Connected! IP:', connectResult.value.ip)
// Fetch JSON from an API
const fetchResult = await fetch('https://jsonplaceholder.typicode.com/posts/1')
if (fetchResult.ok) {
if (!fetchResult.value.ok) {
console.error(`HTTP error: ${fetchResult.value.status}`)
} else {
const data = await fetchResult.value.json()
console.log('Fetched post:', data)
}
} else {
console.error('Fetch failed:', fetchResult.error.name)
}
}
const mem = memoryUsage()
console.log('free heap:', (mem.heapTotal - mem.heapUsed) / 1000 + 'KB')Walkthrough
Country code.
wifi.countrymust be set before connecting. This configures the regulatory domain for your region's WiFi channels.Environment variables. WiFi credentials come from
import.meta.env, which reads from NVS on device. Set them withmikro env set.Connect.
wifi.connect()returns aPromise<Result>. The outerResulttells you if the connection succeeded; thevaluecontains your IP address.Fetch.
fetch()also returns aPromise<Result>. Two levels of error checking:result.ok: did the network request succeed at all?result.value.ok: was the HTTP status in the 2xx range?
Memory. Prints free heap after the request completes, useful for tracking memory on constrained devices.
Run it
npx mikro dev
You should see the WiFi connection, fetched JSON data, and memory usage in the console output.