analogjs / analog

The fullstack meta-framework for Angular. Powered by Vite and Nitro
https://analogjs.org
MIT License
2.57k stars 245 forks source link

Cookies forwarding in load function #606

Closed GuillaumeNury closed 1 year ago

GuillaumeNury commented 1 year ago

Which scope/s are relevant/related to the feature request?

router

Information

Hello!

I use cookies to store authentication token. The fetch function in load does not use original request headers.

Given the following code:

import type { PageServerLoad } from '@analogjs/router';

export const load = async ({ fetch, req }: PageServerLoad) => {
  console.log('req.url', req.url);
  console.log('req.headers', req.headers);
  return {
    principal: await fetch<{ name: string }>('/api/v1/users/me'),
  };
};

It logs:

req.url /_analog/pages/-index-
 An error occurred: FetchError:  (401 Unauthorized (/api/v1/users/me))
req.headers {
  'content-length': '0',
  'user-agent': 'Mozilla/5.0 (Linux x64) node.js/18.15.0 v8/10.2.154.26-node.25',
  host: 'localhost:5173',
  connection: 'close',
  accept: 'application/json, text/plain, */*',
  'x-forwarded-for': '127.0.0.1',
  'x-forwarded-port': '49226',
  'x-forwarded-proto': 'IPv4'
}

Is there any ways of using cookies in load function ?

Describe any alternatives/workarounds you're currently using

Make API calls from client.

I would be willing to submit a PR to fix this issue

brandonroberts commented 1 year ago

Yes, it's possible to do, but we will need to add the event to the PageServerLoad object

Something like below:

import type { PageServerLoad } from '@analogjs/router';

export const load = async ({ fetch, req, event }: PageServerLoad) => {
  const cookies = parseCookies(event);
  console.log('req.url', req.url);
  console.log('req.headers', req.headers);
  return {
    principal: await fetch<{ name: string }>('/api/v1/users/me'),
  };
};

OR

import type { PageServerLoad } from '@analogjs/router';

export const load = async ({ fetch, req, cookies, event }: PageServerLoad) => {
  console.log('req.url', req.url);
  console.log('req.headers', req.headers);
  return {
    principal: await fetch<{ name: string }>('/api/v1/users/me'),
  };
};
GuillaumeNury commented 1 year ago

Oh! It is that easy 🤦 Thank you for the quick reply and keep the good job on Analog!