twa-dev / SDK

npm package for TWA SDK
https://codesandbox.io/s/sdk-kj5961
MIT License
238 stars 21 forks source link

Support for server-side code execution #6

Closed Loskir closed 10 months ago

Loskir commented 1 year ago

I am using Nextjs, which executes the same code on the server and in the browser. When i import @twa-dev/sdk, I get an error window is not defined and there doesn't seem to be a good way to avoid this error. I know that WebApp is not accessible on the server.

ArthurStam commented 10 months ago

I believe that SDK shouldn't be invoked on server side. IMHO, it's application developer responsibility to avoid such executions.

solfKwolf commented 8 months ago

You need to do a dynamic import for the component that is using the 3rd party library. like this example as below:

export default MainButton


+ `app/page.tsx`

```tsx
const MainButton = dynamic(() => import('./components/MainButton'),{ssr:false})

export default function Home() {
  return (<MainButton text="Submit" onClick={() => alert('submitted')} />);
}
kevcube commented 5 months ago

@ivanproskuryakov ^^

corlys commented 5 months ago

Do you know how to do other WebApp functionalities beside MainBitton or BackButton. The dynamic imports does works, but when using WebApp it still got window undefined. I use teh WebApp on a "use client" page but still got the error.

ivanproskuryakov commented 5 months ago

Here is the workaround I came up with:

pages/telegram.tsx

import {useEffect, useState} from 'react';
import { useInterval } from 'usehooks-ts';

declare global {
  interface Window {
    Telegram: any;
  }
}

const Telegram = () => {
  const [timer, setTimer] = useState(0);
  const [isPlaying, setPlaying] = useState<boolean| null>(true)

  let WebApp: any = null;
  let transaction: any = null;

  useInterval(() => {
    setTimer((new Date()).getMilliseconds());
  }, isPlaying ? 1000 : null);

  useEffect(() => {
    if (window !== undefined) {
      WebApp = window?.Telegram?.WebApp;

      if (WebApp) {
        setPlaying(null);
      }
    }
  }, [timer,]);

With telegram-web-app.js added to pages/_app.tsx

<Script
    src="https://telegram.org/js/telegram-web-app.js"
     strategy="afterInteractive"
/>