Web NFC API Explained: How to Write NFC Tags Directly from the Browser (Step-by-Step Guide)

Web NFC API Explained: How to Write NFC Tags Directly from the Browser (Step-by-Step Guide)

Web NFC API Explained: How to Write NFC Tags Directly from the Browser (Step-by-Step Guide)

Let’s be honest for a second: downloading a 50MB native app just to write a simple URL onto an NFC tag feels ridiculous. It’s 2026. We shouldn’t need a specialized toolkit installed on our phones to do something as basic as flipping a bit on a piece of plastic.

For the longest time, though, that was the reality. If you wanted to mess with Near Field Communication (NFC), you were stuck in the walled gardens of Android Java or Swift. The browser was off-limits. Sandbox rules, security paranoia—pick your poison.

But the web moves fast. With the Web NFC API, Chrome on Android has basically kicked the door down. You can now read and—more importantly—write NFC tag from browser sessions directly. No app stores. No "allow installation from unknown sources." Just JavaScript.

I’ve spent the last few years tinkering with hardware-web bridges, and getting this to work reliably can be finicky if you don't know the quirks. So, I’m going to walk you through how to build a Web NFC API tutorial that actually works, covering everything from the NDEF record JavaScript example to why your iPhone-using friends are going to be jealous (or annoyed).


Wait, What Actually is the Web NFC API?

Strip away the buzzwords, and it’s pretty simple. The Web NFC API allows your browser’s active tab to communicate with NFC tags when they are tapped against the back of the device. It focuses specifically on NDEF (NFC Data Exchange Format) messages.

It’s part of the broader "Fugu" project by Google—an initiative to give the web the same capabilities as native apps. The goal? To make it so you never have to open the Play Store again for utility tasks.

Here is the kicker though: It’s not a background process. You can’t build a web page that silently scans for credit cards in someone's pocket while they read a blog post. The API requires an active "session," usually triggered by a button click, and the window must be in focus. It's safe, but it requires user intent.

The Elephant in the Room: Browser Support (Chrome Android & The Rest)

Before you copy-paste the code below, check your pockets. What phone is in there?

  • Android (Chrome/Edge/Opera): You are golden. Support is robust.
  • iOS (Safari): Crickets. Apple hasn't implemented this yet, citing privacy concerns (though many suspect it's to protect their App Store ecosystem).
  • Desktop: Generally no, unless you have specific USB NFC readers and developer flags enabled, but really, this is a mobile-first feature.

If you're building a commercial solution, this Web NFC Chrome Android limitation is your biggest hurdle. You can't target everyone. But for internal business tools, inventory management, or hobbyist projects? It’s a game-changer.

Understanding NDEF Records (The "File System" of NFC)

You can't just throw raw text at a tag. You have to package it. We use NDEF records. Think of an NDEF message like a folder, and records are the files inside it.

The most common types you’ll deal with are:

  • Text Record: Plain strings. Good for ID codes.
  • URL Record: Opens a website when scanned. This is the bread and butter of marketing tags.
  • JSON Record: Yes, you can serialize JSON and store it on a tag. Amazing for passing complex state between devices without a server.
Pro Tip: If you find dealing with NDEF structures tedious (and they can be), tools like QR to NFC Converter can bridge the gap, handling the encoding logic for you so you don't have to manually construct byte arrays.

Step-by-Step: Writing to a Tag with JavaScript

Alright, let’s get into the code. A lot of old tutorials reference an `NDEFWriter` interface. Forget that. It’s dead. The spec was updated, and now `NDEFReader` handles both reading and writing. Confusing naming? Absolutely. But that’s web standards for you.

1. The Setup

First, we need a button. Never try to trigger this on page load—the browser will block it immediately.

<button id="writeBtn">Write to Tag</button>
<p id="status"></p>

2. The "Write" Function

Here is a modern, async/await implementation of an NDEF record JavaScript example.

document.getElementById("writeBtn").addEventListener("click", async () => {
  const status = document.getElementById("status");

  // Feature detection: Don't let iOS users hang
  if (!("NDEFReader" in window)) {
    status.innerText = "Web NFC is not available on this device/browser. Try Chrome on Android.";
    return;
  }

  try {
    // 1. Initialize the reader
    const ndef = new NDEFReader();

    // 2. Prompt the user to tap
    status.innerText = "Scanning... Tap your NFC tag now.";

    // 3. Prepare the payload
    // We're writing a simple URL here.
    await ndef.write({
      records: [{ recordType: "url", data: "https://www.qrcartoon.com/" }]
    });

    status.innerText = "Success! Tag written.";
    
  } catch (error) {
    status.innerText = "Write failed: " + error;
    console.error(error);
  }
});

Breakdown of the Code

Feature Detection: The `if (!("NDEFReader" in window))` check is crucial. Without it, your script crashes on Safari.

The Await Call: `ndef.write()` is a Promise. When you call it, the phone starts polling the NFC hardware. The UI will usually show a system overlay saying "Ready to scan." The Promise only resolves once the user actually taps the tag and the data is transferred.

Complex Data? If you want to write plain text or JSON, just change the object:

await ndef.write({
  records: [
    { recordType: "text", data: "InventoryID: 12345" },
    { recordType: "json", data: { sku: "ABC-99", location: "Warehouse 1" } }
  ]
});

How to Read NFC Tags via Web NFC

Reading is slightly more event-driven. You start the scan, and then listen for "reading" events. It feels a bit like listening for keystrokes.

const ndef = new NDEFReader();
await ndef.scan();

ndef.addEventListener("reading", ({ message, serialNumber }) => {
  console.log(`Tag Serial: ${serialNumber}`);
  
  for (const record of message.records) {
    console.log("Record type:  " + record.recordType);
    console.log("MIME type:    " + record.mediaType);
    // You'll need a TextDecoder to read the data
    const textDecoder = new TextDecoder(record.encoding);
    console.log("Data: " + textDecoder.decode(record.data));
  }
});

This snippet is powerful. You can extract the unique serial number of the tag (great for security) and iterate through every record stored on it.

Limitations and Headaches (The "Gotchas")

I’ve banged my head against the desk enough times to save you the trouble. Here are the constraints you need to know:

  1. HTTPS Required: You cannot test this on `http://localhost` unless you are doing port forwarding or local overrides. It strictly requires a secure context.
  2. Screen Lock: The API stops working the second the screen goes off. You can't build a background logger.
  3. Tag Formatting: Web NFC can generally write to unformatted tags, but if a tag is locked or corrupted, the browser often throws a generic `NetworkError`. It’s not very descriptive.
  4. Data Size: Most cheap tags (NTAG213) only hold about 144 bytes. Don't try to write a novel. Stick to a short URL or ID.

NFC vs QR Codes: The "Contactless" Showdown

Clients always ask me: "Why bother with NFC when QR codes are free?"

It’s a valid question. QR codes are visual; anyone with a camera can scan them. But they require light, focus, and—let's be real—they can look ugly on premium packaging.

NFC is magical. It feels premium. You tap, and it works. No camera app, no focusing. However, it costs money per unit (usually 10-50 cents).

Interestingly, the line is blurring. Platforms like QR Cartoon are increasingly integrating both. You might have a visual QR code for iPhone users and an embedded NFC chip for Android power users, both pointing to the same campaign. It’s not an "either/or" anymore; it’s a "yes, and."

Real-World Business Use Cases

Where are people actually using NFC tag programming without app dependencies?

1. Museum & Gallery Guides

Instead of forcing visitors to download an "Audio Guide App" they will delete 10 minutes later, museums glue NFC tags next to paintings. Tap, and the browser loads the audio file. Frictionless.

2. Restaurant Ordering

QR codes on tables are standard now, but NFC is faster. A coaster with an embedded tag launches the menu instantly. Plus, unlike a QR sticker, it doesn't get worn out or scratched into unreadability.

3. Equipment Maintenance

I worked on a project where technicians tapped their phone to a generator's NFC tag. It opened a web form pre-filled with that generator's ID, ready for them to log the repair. No typing serial numbers, no errors.

FAQ: Web NFC Nitty-Gritty

Do I need an external NFC writer hardware?

Nope. If you have an Android phone made in the last 5 years, the hardware is already in your hand. The Web NFC API leverages the phone's internal antenna.

Can I make an NFC tag read-only (locked) using the browser?

Currently, the Web NFC API spec includes a `makeReadOnly()` method, but support is spotty. It’s risky—if you lock it with the wrong data, that tag is bricked forever. Proceed with caution.

Why isn't my tag scanning?

Is your metal phone case blocking it? Is the tag on a metal surface? (Metal interferes with NFC fields). Are you holding it near the camera array? (That’s usually where the antenna is). It’s often a physics problem, not a code problem.

Is there a way to generate QR codes that link to these NFC triggers?

Absolutely. You can create a workflow where a QR code acts as a fallback. Check out QR Cartoon's generator to create the visual entry point that matches your NFC data.

Conclusion

The Web NFC API represents a massive shift in how we interact with the physical world. It takes the power of hardware interaction and democratizes it, moving it from compiled, gate-kept applications to the open web.

Sure, the lack of iOS support is a pain. It really is. But for the billions of Android devices out there, the bridge between physical objects and digital experiences just got a lot shorter.

If you’re a developer, grab a pack of NTAG215 stickers (they’re cheap online), fire up Chrome, and try the code above. There is something undeniably cool about writing data to a physical object using nothing but JavaScript.

And if you’d rather not mess with `Async/Await` and just want to get the job done, tools like the QR to NFC Converter are there to save you the headache.

Go build something real.

Tags: web nfc api tutorial, write nfc tag from browser, nfc javascript api, ndefwriter example, chrome android nfc, web nfc limitations

Comments

Popular posts from this blog

Why QR Codes Are the Unsung Hero of Modern SaaS and Marketing