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})
// ...
}
// 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 />;
}
// 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 - https://github.com/vercel/next.js/discussions/14086 - https://stackoverflow.com/questions/70950877/next-js-typescript-window-in-not-defined In some parts of my zustand store I need to use the context
// store.ts
// ...
const node = context.createOscillator();
// 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?
Integrating React Flow and the Web Audio API – React Flow
React Flow - Customizable library for rendering workflows, diagrams and node-based UIs.
GitHub
Creating AudioContext() · vercel next.js · Discussion #14086
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
Next.js typescript "window" in not defined
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
1 Reply
ott
ott9mo ago
There was someone else doing something similar with zustand and audio context in the server (search for AudioContext) which is where I got the idea for the setup on my store, but I want to know if there is a better way.
Want results from more Discord servers?
Add your server