Back

[SOLVED] window is not defined - client sdk

  • 0
  • Web
Faye
18 Apr, 2024, 11:15

Heyo.

This is a continuation of #Server Action Not Working?.

TL;DR
The developer encountered a 'window is not defined' error using the Appwrite client SDK in a client-side component within NextJS. The issue was resolved after tweaking the code and ensuring that the client.subscribe function was used correctly. The error occurred due to server-side execution when it should have been client-side. The issue was similar to one previously fixed in Appwrite's web SDK. An upcoming release will address the problem caused by 'isomorphic-form-data'.
Faye
18 Apr, 2024, 11:16

the code using appwrite.ts:

TypeScript
import {
  Client,
  Account,
  Teams,
  Databases,
  Storage,
  Functions,
  Messaging,
  Locale,
  Avatars,
} from 'appwrite'

export const client = new Client()
  .setEndpoint(`${process.env.NEXT_PUBLIC_API_URL}/v1`)
  .setProject(`${process.env.NEXT_PUBLIC_APPWRITE_PROJECT_ID}`)

export const account: Account = new Account(client)
export const teams: Teams = new Teams(client)
export const databases: Databases = new Databases(client)
export const storage: Storage = new Storage(client)
export const functions: Functions = new Functions(client)
export const messaging: Messaging = new Messaging(client)
export const locale: Locale = new Locale(client)
export const avatars: Avatars = new Avatars(client)

export { ExecutionMethod, ID, Query } from 'appwrite'
Faye
18 Apr, 2024, 11:17

Having a page on SSR, with a client component imported using for example this kind of code:

TypeScript
'use client'
import { storage } from '@/app/appwrite-client'

export default function FetchGallery({ name, gallery }) {
  const getGalleryImageUrl = (galleryId: string) => {
    console.log(galleryId)
    if (!galleryId) return
    const imageId = storage.getFileView('655ca6663497d9472539', `${galleryId}`)
    return imageId.href
  }

  const url = getGalleryImageUrl(gallery?.galleryId)
  console.log(url)

  // The rest of the component remains unchanged with conditional rendering based on the data's availability.
  return (
    <img
      src={url}
      alt={name || 'Image'}
      className={`imgsinglegallery mx-auto h-[400px] w-auto max-w-full rounded-lg object-contain`}
    />
  )
}

Will spam "window is not defined" every time you refresh the page.

xmaniaxz
18 Apr, 2024, 23:29

example of mine:

TypeScript
//database.jsx

import { account, client, database, storage, teams, userId } from "@/utils/appwrite";
import { Query,ID } from "appwrite";
import { publish } from "./events";

export async function GetServerSpells(IncomingFilters) {
  const activeFilters = IncomingFilters || [];
  const queryOptions = [Query.limit(850)];
  if (activeFilters.length > 0) {
    //Include active filters in the query
    activeFilters.forEach((filter) => {
      switch (filter[0]) {
        case "SpellName":
          //console.log(`Database.jsx: Got: SpellName with filters ${filter[0]} | ${filter[1]}}`)
          queryOptions.push(Query.search(filter[0], `./${filter[1]}/`));
          break;
        case "Class":
          queryOptions.push(Query.search(filter[0], filter[1]));
          break;
        default:
          queryOptions.push(Query.equal(filter[0], filter[1]));
          break;
      }
    });
  }
  //console.log(`trying to find spells with filters: ${queryOptions}`);
  const x = await database.listDocuments(
    process.env.NEXT_PUBLIC_DATABASE_ID,
    process.env.NEXT_PUBLIC_COLLECTION_SPELL_ID,
    queryOptions
  );
  const list = await SortSpells(x["documents"]);
  //console.log(`Database.jsx: Found list: ${JSON.stringify(list)}`);
  return list;
}
xmaniaxz
18 Apr, 2024, 23:31
TypeScript
//spelllist.jsx
"use client"
import { useState, useEffect } from "react";
import { GetServerSpells } from "@/utils/Database";


  const data = async () => {
    setSpellData(await GetServerSpells());
  };
  useEffect(() => {
    data();
  }, []);
xmaniaxz
18 Apr, 2024, 23:31

Now this is javascript but it might to the same for typescript

xmaniaxz
18 Apr, 2024, 23:31

cause client to server is just not possible with nextjs

Steven
18 Apr, 2024, 23:53

i think you can do the same thing with the node sdk now

Faye
18 Apr, 2024, 23:56

So just use a server action?

Faye
19 Apr, 2024, 00:01

I'll try out some stuff tomorrow.

Faye
30 Apr, 2024, 14:36

Does realtime work using the node sdk? 🤔

Steven
30 Apr, 2024, 16:21

No. Please create a new post for different topics

Faye
30 Apr, 2024, 16:45

Well, it's still the same topic. You just wanted me to use something else.

Steven
30 Apr, 2024, 19:47

Your original topic was using node sdk and getting window not defined. The new topic is about realtime

Faye
30 Apr, 2024, 19:57

Well, my issue is still about window is not defined, because I basically am not allowed to use the appwrite sdk in any way, to not get the error.

Faye
30 Apr, 2024, 19:59

I can try with realtime, but I figure that everything is built the same way and something in the appwrite client sdk shows that error. So far everything else has given the error, so expected is that realtime of all things, will too.

loks0n
3 May, 2024, 08:10

It's spamming on the server console, not the browser right?

Faye
3 May, 2024, 08:16

Both

Faye
3 May, 2024, 08:16
loks0n
3 May, 2024, 08:19

Right. Like xmaniaxz suggested, I think you need to put calls to the @/app/appwrite-clietn inside a useEffect, that also checks window !== undefined

loks0n
3 May, 2024, 08:21

We might be able to solve this in the SDK by not depend on window. We can do is throw a more descriptive error. Is it just the getFileView endpoint you see this with? Or all services/endpoints

Faye
3 May, 2024, 08:22

All, just make a simple createEmailPasswordSession auth page

Faye
3 May, 2024, 08:22

the moment I try to use the client sdk, basically

loks0n
3 May, 2024, 08:27

Right, it's not easy to see where that faulty window access comes from unfortunately, but I will take some time today to track it down

Faye
14 May, 2024, 12:02

Hey!

Did you come closer towards tracking it down?

Reply

Reply to this thread by joining our Discord

Reply on Discord

Need support?

Join our Discord

Get community support by joining our Discord server.

Join Discord

Get premium support

Join Appwrite Pro and get email support from our team.

Learn more