question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Server-side `fetch` in `load` is not credentialed

See original GitHub issue

Describe the bug No credentials are passed on in a server-side fetch.

To Reproduce On a fresh kit project:

<!-- src/routes/index.svelte -->
<script context="module">
  export async function load({ fetch }) {
    await fetch(`http://localhost:3000/test`, {
      credentials: "include",
      mode: "cors",
    });
    return true;
  }
</script>

<h1>blah</h1>
// src/routes/test.js
export async function get(request) {
  console.log(request);
  return {
    body: {
      data: 1234,
    },
  };
}
// src/setup/index.js
export async function prepare() {
  return {
    headers: {
      "Set-Cookie": "test=1234",
    },
  };
}

Load http://localhost:3000 twice.

Expected behavior Cookie header should appear in server console on second load.

Information about your SvelteKit Installation:

  System:
    OS: Windows 10 10.0.19042
    CPU: (16) x64 AMD Ryzen 7 3700X 8-Core Processor
    Memory: 12.38 GB / 31.95 GB
  Binaries:
    Node: 14.16.0 - C:\Program Files\nodejs\node.EXE
    Yarn: 1.22.10 - ~\AppData\Roaming\npm\yarn.CMD
    npm: 7.6.1 - C:\Program Files\nodejs\npm.CMD
  Browsers:
    Chrome: 89.0.4389.90
    Edge: Spartan (44.19041.423.0), Chromium (89.0.774.54)
    Internet Explorer: 11.0.19041.1
  npmPackages:
    @sveltejs/kit: next => 1.0.0-next.59
    svelte: ^3.29.0 => 3.35.0

Severity Blocking for any project that requires credentialed server-side requests.

Issue Analytics

  • State:closed
  • Created 2 years ago
  • Reactions:5
  • Comments:30 (16 by maintainers)

github_iconTop GitHub Comments

17reactions
sphinxc0recommented, Apr 19, 2021

This feels like a common use case for SvelteKit. I want to write my frontend in SvelteKit and have a separate api. What would be the optimal way to do this? Using token-based auth? Something else?

5reactions
schibrikovcommented, Apr 17, 2021

This is a blocker for me as well, as I don’t really understand how to interact with my backend while it’s not implemented within sveltekit and uses cookie-based authentication.

I don’t know how much workaround is it, but for now I’m using this approach:

myproject/src/routes/api/[…route].ts:

import fetch from 'node-fetch';
import type { RequestHandler } from '@sveltejs/kit';

const apiUrl = 'http://localhost:5000';

const handler: RequestHandler = async function (request) {
	const response = await fetch(apiUrl + request.path, {
		headers: request.headers,
		method: request.method
	});

	let body: unknown;

	try {
		body = await response.clone().json();
	} catch (e) {
		body = await response.text();
	}

	const headers = {
		'set-cookie': response.headers.get('set-cookie')
	};

	return {
		status: response.status,
		headers,
		body
	};
};

export const get: RequestHandler = handler;

This way I’m able to pass cookie back and forth, so this code kind of works:


<script lang="ts" context="module">
	import type { Load } from '@sveltejs/kit';
	export const load: Load = async (input) => {
		const resp = await input.fetch(`/api/auth/me`);
		const me = await resp.json();
		return {
			props: { me }
		};
	};
</script>

<script lang="ts">
	export let me: any;
</script>

{JSON.stringify(me)}

Doesn’t seem to me as an optimal approach, because in involves some manual parsing and non-obvious assumptions. Hope for some solution from @Rich-Harris as well.

Read more comments on GitHub >

github_iconTop Results From Across the Web

How to fetch data from Firebase in getServerSideProps with ...
It needs to access to fs module which is not available on client side. If you need firebase in client side use @firebase/app...
Read more >
Reason: Credential is not supported if the CORS header ...
If using Server-sent events, make sure EventSource.withCredentials is false (it's the default value). If using the Fetch API, make sure Request.
Read more >
Loading data • Docs • SvelteKit
To get data from an external API or a +server.js handler, you can use the provided fetch function, which behaves identically to the...
Read more >
Google Sign-In for server-side apps | Authentication
Step 3: Initialize the GoogleAuth object. Load the auth2 library and call gapi.auth2.init() to initialize the GoogleAuth object. Specify your client ...
Read more >
Different ways to fetch data in Next.js (server-side) and when ...
If each page in your app uses getStaticProps (or no server-side data ... to loading the page and fetching the data on the...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found