Creating `AudioContext` in Next.js

I've had quite a lot of trouble creating an AudioContext object in my nextjs project. I'm expanding on the ReactFlow Audio API guide https://reactflow.dev/learn/tutorials/react-flow-and-the-web-audio-api which uses ReactFlow as a UI to connect AudioNodes.

I have a component that contains my ReactFlow component that I dynamically load in with {ssr: false} on a page. There's a snippet at the top of the flow file
// flow.tsx
let ctx: AudioContext | undefined = undefined;
if (typeof window !== "undefined") {
  ctx = new AudioContext();
}
export default function Flow() {
  if (!ctx) {
    return null;
  }  
  store.setup({ctx})
  // ...
}

(that I think should only run once, but I'm not sure)
// page.tsx
"use client";

import dynamic from "next/dynamic";

const DynamicFlow = dynamic(() => import("~/components/flow"), {
  loading: () => <div>Loading</div>,
  ssr: false,
});

export default function FlowPage() {
  return <DynamicFlow />;
}


There isn't a lot of documentation on this, I've read
In some parts of my zustand store I need to use the context
// store.ts
// ...
const node = context.createOscillator();


What/where is the best way to construct an AudioContext object, and is there any way for me to always have a valid AudioContext in my zustand store?
React Flow - Customizable library for rendering workflows, diagrams and node-based UIs.
GitHub
I'm able to instantiate a new AudioContext() inside useEffect() but I'm not sure the best approach for exporting a singular AudioContext() object. const Oscillator = ({ frequency, type }) =...
Stack Overflow
Hi I am declaring an audio context like this and it says window in undefined. I tried declaring declare const window :any above window.Context but the error's still there. Anyone know how I can solve
Was this page helpful?