This is an expo project that I'm working with on web. It attempts to authenticate with Spotify Web API. The access token is returned from the Spotify authentication page and is available inside the callback on req.user.accessToken.
However, in other routes called subsequently the req.user.accessToken and req.session.accessToken are both undefined. This is despite the attempt made inside the callback to assign the token to the session.
Here, the access token is available inside the authentication callback...
app.get(
"/auth/spotify/callback",
passport.authenticate("spotify", { failureRedirect: "/" }),
(req, res) => {
req.session.accessToken = req.user.accessToken;
console.log("callback: " + req.session.accessToken);
res.redirect("http://localhost:8081");
}
);
But not in other routes
app.get("/spotify/get-currently-playing", async (req, res) => {
try {
const accessToken = req.session && req.session.accessToken;
if (!accessToken) {
throw new Error("Access token not found");
}
const userData = await getCurrentSongInfo(accessToken);
res.json(userData);
...
The middleware is setup earlier on as follows
app.use(
session({
secret: "x",
resave: false,
saveUninitialized: false,
})
);
app.use(passport.initialize());
app.use(passport.session());
passport.use(
new SpotifyStrategy(
{
clientID: "x",
clientSecret: "x",
callbackURL: "http://localhost:5001/auth/spotify/callback",
},
(accessToken, refreshToken, expires_in, profile, done) => {
// Store the access token in the session
if (accessToken) {
profile.accessToken = accessToken;
console.log(profile);
done(null, profile);
} else {
done(new Error("Failed to retrieve access token"));
}
}
)
);
You need to get from user session data
FROM
TO
Other routes also same method of access
Demo code
package.jsonFile tree
How to get
client_id,client_secretandredirect_uriOpen URL by browser
Save as
server.jswith your Client ID/secret and redirect URI.HTML files
account.htmlindex.htmllayout.htmllogin.htmlResult
In server terminal