Creating a custom module to support Web NFC in NextJS projects (TypeScript). Add the following code to your project to be able to compile and run the Web NFC API in NextJS.
Declare the module in a .d.ts
file in the root of your project or in the types
directory.
declare module 'web-nfc' {
interface Window {
NDEFMessage: NDEFMessage
}
...
}
import {NDEFReader} from "web-nfc";
// ...
try {
if ("NDEFReader" in window) {
const ndef = new NDEFReader();
await ndef.scan(); // Start NFC scan
console.log("Scan started successfully.");
ndef.onreading = (event) => {
const { message } = event;
console.log("NFC reading detected.");
for (const record of message.records) {
if (record.recordType === "text") {
const decoder = new TextDecoder("utf-8");
const data = decoder.decode(record.data);
console.log("NFC Data:", data);
// Process NFC data
}
}
};
ndef.onreadingerror = () => {
console.error("Failed to read NFC data.");
};
} else {
alert("Web NFC is not supported on this device/browser.");
}
} catch (error) {
console.error("Error accessing NFC:", error);
}