Skip to content
This repository was archived by the owner on Jan 11, 2023. It is now read-only.

$session prop token is not defined even if it is set on the browser (sapper/svelte app deployed on Netlify - Nodejs app deployed on heroku) #1796

Description

@work-state

login POST request

  async function login(method, token, api_url, path, cred) {
	  const opts = {
		  method,
		  headers: {
			  Accept: "application/json, text/plain, */*",
			  "Content-Type": "application/json",
			  cookie: `ts_09=${token}`,
		  },
		  credentials: "include",
	  };
	  if (cred) {
		  opts.body = JSON.stringify(cred);
	  }
	  let url = new URL(`${api_url}/api/${path}`);

	try {
		const res = await fetch(url, opts);
		const data = await res.json();
		if (res.status !== 200) throw data;
		try {
			return data;
		} catch (ex) {
			return data;
		}
	} catch (ex) {
		throw ex;
	}
}

login Route, which at the end I send to the browser a cookie that contains a token

router.post("/log", async (req, res) => {
	try {
		const { email, password } = req.body;
		const user = await User.verifyCredentials(email, password);
		const token = await user.generateAuthToken();
		res
		    .cookie("ts_09", token, {
			    httpOnly: process.env.NODE_ENV === "production" ? false : true,
			    secure: process.env.NODE_ENV === "production" ? true : false,
			    maxAge: 24 * 60 * 60 * 1000,
		    })
		    .json("done");
	} catch (err) {
		res.json(err);
	}
});

sapper-app/src/server.js

polka()
	.use(
		compression({ threshold: 0 }),
		sirv("static", { dev }),
		cookieParser(),
		(req, res, next) => {
			const token = req.cookies["ts_09"];
			const profile = token ? jwt.decode(token) : false;
			return sapper.middleware({
				session: () => {
					return {
						authenticated: !!profile,
						profile,
						token,
					};
				},
			})(req, res, next);
		}
	)

When I try to sign in with credentials, it sends a post request, then performs a check, and at the end of it a cookie is sent from backend to the browser. In Dev Tools I can see the stored token, but when I try to console log the token it shows me "undefined"

sapper-app/src/routes/index.svelte

<script>
	import { stores } from "@sapper/app";

	const { session } = stores();

	console.log($session); // output : {authenticated: false, profile: false, token: undefined}
</script>

i don't know exactly what i missed, but locally it works fine

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions