Back

[SOLVED] Setting cookies

  • 0
  • Accounts
  • Web
djcali
15 Aug, 2023, 14:51

When creating an anonymous session server side I can set cookies this way:

TypeScript
    default: async ({ fetch, cookies }) => {
        try {
            const response = await fetch(`${AppwriteEndpoint}/account/sessions/anonymous`, {
                method: 'POST',
                headers: {
                    'x-appwrite-project': AppwriteProject
                }
            });

            const json = await response.json();

            if (json.code >= 400) {
                return fail(400, { message: json.message });
            }

            const ssrHostname = SsrHostname === 'localhost' ? SsrHostname : '.' + SsrHostname;
            console.log(`ssrhostname = ${ssrHostname}`);
            const appwriteHostname =
                AppwriteHostname === 'localhost' ? AppwriteHostname : '.' + AppwriteHostname;
            console.log(`appwritehostname = ${appwriteHostname}`);

            const cookiesStr = (response.headers.get('set-cookie') ?? '')
                .split(appwriteHostname)
                .join(ssrHostname);

            const cookiesArray = setCookie.splitCookiesString(cookiesStr);
            const cookiesParsed = cookiesArray.map((cookie) => setCookie.parseString(cookie));

            for (const cookie of cookiesParsed) {
                cookies.set(cookie.name, cookie.value, {
                    domain: cookie.domain,
                    secure: cookie.secure,
                    sameSite: cookie.sameSite as any,
                    path: cookie.path,
                    maxAge: cookie.maxAge,
                    httpOnly: cookie.httpOnly,
                    expires: cookie.expires
                });
                console.log(`cookie: ${cookie.domain}`);
                console.log(`cookie: ${cookie.path}`);
            }
            return json;
        } catch (err: any) {
            return fail(400, { message: err.message });
        }
    }
} satisfies Actions;```
TL;DR
The user had an issue with setting cookies and was looking for help. They found the solution in the provided documentation and thanked the person who helped them. The discussion also covered topics such as REST API documentation, examples for fetch, response body, and creating sessions. There is no specific solution outlined in the thread.
djcali
15 Aug, 2023, 14:52

I want to do the same kind of logic when a user logs in. How can I achieve this.

TypeScript
                body.email as string,
                body.password as string 

I see that I get a session object back.

Drake
15 Aug, 2023, 15:37

you need to manually make the API call just like how your sample code manually called the anonymous session endpoint so that you can grab the cookie the same way

djcali
15 Aug, 2023, 16:23

Ok, here is what i have so far. Hope it is in the right direction:

TypeScript
let payload: Payload = {};

if (typeof body.email !== 'undefined') {
  payload['email'] = body.email;
}

if (typeof body.password !== 'undefined') {
  payload['password'] = body.password;
}

const response = await fetch(`${AppwriteEndpoint}/account/sessions/email`, {
  method: 'POST',
  headers: {
    'x-appwrite-project': AppwriteProject
  },
  body: JSON.stringify(payload)                
});

console.log(response);

I'm just not sure on where to put the payload?

djcali
15 Aug, 2023, 16:23

I'm getting back a bad request.

TypeScript
  [Symbol(realm)]: null,
  [Symbol(state)]: {
    aborted: false,
    rangeRequested: false,
    timingAllowPassed: true,
    requestIncludesCredentials: true,
    type: 'default',
    status: 400,
    timingInfo: {
      startTime: 67667657.25008106,
      redirectStartTime: 0,
      redirectEndTime: 0,
      postRedirectStartTime: 67667657.25008106,
      finalServiceWorkerStartTime: 0,
      finalNetworkResponseStartTime: 0,
      finalNetworkRequestStartTime: 0,
      endTime: 0,
      encodedBodySize: 114,
      decodedBodySize: 0,
      finalConnectionTimingInfo: null
    },
    cacheState: '',
    statusText: 'Bad Request',
    headersList: HeadersList {
      cookies: null,
      [Symbol(headers map)]: [Map],
      [Symbol(headers map sorted)]: null
    },
    urlList: [ [URL] ],
    body: { stream: undefined }
  },
  [Symbol(headers)]: HeadersList {
    cookies: null,
    [Symbol(headers map)]: Map(19) {
      'access-control-allow-credentials' => [Object],
      'access-control-allow-headers' => [Object],
      'access-control-allow-methods' => [Object],
      'access-control-allow-origin' => [Object],
      'access-control-expose-headers' => [Object],
      'cache-control' => [Object],
      'content-encoding' => [Object],
      'content-length' => [Object],
      'content-type' => [Object],
      'date' => [Object],
      'expires' => [Object],
      'pragma' => [Object],
      'server' => [Object],
      'x-content-type-options' => [Object],
      'x-debug-fallback' => [Object],
      'x-debug-speed' => [Object],
      'x-ratelimit-limit' => [Object],
      'x-ratelimit-remaining' => [Object],
      'x-ratelimit-reset' => [Object]
    },
    [Symbol(headers map sorted)]: null
  }
}
Drake
15 Aug, 2023, 17:26

what's the response body?

Drake
15 Aug, 2023, 17:27

btw, it's helpful to include the language when adding multiline code so you have syntax highlighting

djcali
15 Aug, 2023, 17:28

not sure how to do that

djcali
15 Aug, 2023, 17:30

body: { stream: undefined }

Drake
15 Aug, 2023, 17:30

have you looked at any documentation for fetch?

djcali
15 Aug, 2023, 17:32

So when i do : console.log(JSON.stringify({payload}));

The body is : {"payload":{"email":"example@test.com","password":"password"}}

djcali
15 Aug, 2023, 17:36

Yeah I looked at the REST, no example shows up to see how it works

Drake
15 Aug, 2023, 17:37

switch the version to 1.3

Drake
15 Aug, 2023, 17:37

Make sure to also read the REST api docs: https://appwrite.io/docs/rest

djcali
15 Aug, 2023, 17:39

ahhhh That's what i needed. Thanks.

djcali
15 Aug, 2023, 18:04

Thank You Seven for you patience with this. Those docs solved my issue.

djcali
15 Aug, 2023, 18:04

[SOLVED] Setting cookies

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