sapper
sapper copied to clipboard
$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)
trafficstars
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