Skip to content

WiFi + Fetch

Connect to a WiFi network and make an HTTP request to a JSON API.

APIs used: wifi, fetch, sys

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

ts
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

  1. Country code. wifi.country must be set before connecting. This configures the regulatory domain for your region's WiFi channels.

  2. Environment variables. WiFi credentials come from import.meta.env, which reads from NVS on device. Set them with mikro env set.

  3. Connect. wifi.connect() returns a Promise<Result>. The outer Result tells you if the connection succeeded; the value contains your IP address.

  4. Fetch. fetch() also returns a Promise<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?
  5. 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.

View source on GitHub