How do you send an authenticated request?

I'm either blind or confused, from the docs I can't find anything on how to send a request to a backend (ExpressJS) in this case for a simple protected route. I can login/logout, but if I attached the token in a header "Authorization" : Bearer ${token} and my middleware looks like the following
export default async function requireAuth(req: Request, _res: Response, next: NextFunction) {
try {
const session = await auth.api.getSession({
headers: fromNodeHeaders(req.headers),
});

if (!session || !session.user || !session.session) {
throw new UnauthorizedError();
}

req.user = session.user as User;
req.session = session.session as Session;

next();
} catch (err) {
next(new UnauthorizedError("Invalid or expired session"));
}
}
export default async function requireAuth(req: Request, _res: Response, next: NextFunction) {
try {
const session = await auth.api.getSession({
headers: fromNodeHeaders(req.headers),
});

if (!session || !session.user || !session.session) {
throw new UnauthorizedError();
}

req.user = session.user as User;
req.session = session.session as Session;

next();
} catch (err) {
next(new UnauthorizedError("Invalid or expired session"));
}
}
I get a 401, what am I missing? FYI this is for the email + password plugin only. --- Edit I should add my frontend app is Nextjs with axios, Here's how my axios is setup
api.interceptors.request.use(
(config) => {
// This code will only run on the client-side
if (typeof window !== "undefined") {
const token = localStorage.getItem("bearer_token");
if (token) {
config.headers["Authorization"] = `Bearer ${token}`;
}
}
return config;
},
(error) => {
return Promise.reject(error);
}
);
api.interceptors.request.use(
(config) => {
// This code will only run on the client-side
if (typeof window !== "undefined") {
const token = localStorage.getItem("bearer_token");
if (token) {
config.headers["Authorization"] = `Bearer ${token}`;
}
}
return config;
},
(error) => {
return Promise.reject(error);
}
);
1 Reply
highzenburger
highzenburgerOP5mo ago
Got it to work, I just realized it's cookies not bearer tokens for auth. Would love a simple example, I always find your docs neat but confusing. Especially the flipping between baclend and frontend clients.

Did you find this page helpful?