S
SolidJS•5mo ago
AlberTenez

How can I pass data from middleware to frontend on solid-start.

I have this middleware to validate a user accesstoken. And the response provides me the name of the user and the validity of the token. While I handle the redirects if valid or not from the middleware. I would like to use the user name in the app layout. How could I pass it down to the client? I can't find a nice solution for it.
export default createMiddleware({
onRequest: [
async (event) => {
const { pathname } = new URL(event.request.url);
const isProtectedLoggedOut = protectedPathsLogOut.some((protectedPath) =>
pathname.startsWith(protectedPath),
);
const isProtectedLoggedIn = protectedPathsLogIn.some((protectedPath) =>
pathname.startsWith(protectedPath),
);
const accessToken = getServerCookie('access-token', event);
if (accessToken) {
const response = await fetchApi<GetUser>('/users', 'get', undefined, {
authorization: `Bearer ${accessToken}`,
});

if (!response.success) {
deleteCookie(event, 'access-token');

if (isProtectedLoggedOut) {
return sendRedirect(event, '/account/login');
}
}

if (response.success) {
if (isProtectedLoggedIn) {
return sendRedirect(event, '/account/private');
}

event.locals.user = response.data;
}
} else if (isProtectedLoggedOut) {
return sendRedirect(event, '/account/login');
}
},
],
});
export default createMiddleware({
onRequest: [
async (event) => {
const { pathname } = new URL(event.request.url);
const isProtectedLoggedOut = protectedPathsLogOut.some((protectedPath) =>
pathname.startsWith(protectedPath),
);
const isProtectedLoggedIn = protectedPathsLogIn.some((protectedPath) =>
pathname.startsWith(protectedPath),
);
const accessToken = getServerCookie('access-token', event);
if (accessToken) {
const response = await fetchApi<GetUser>('/users', 'get', undefined, {
authorization: `Bearer ${accessToken}`,
});

if (!response.success) {
deleteCookie(event, 'access-token');

if (isProtectedLoggedOut) {
return sendRedirect(event, '/account/login');
}
}

if (response.success) {
if (isProtectedLoggedIn) {
return sendRedirect(event, '/account/private');
}

event.locals.user = response.data;
}
} else if (isProtectedLoggedOut) {
return sendRedirect(event, '/account/login');
}
},
],
});
The information I'm interested in lives in response.data: event.locals.user = response.data; Any help will be appreciated. Thanks!!!
2 Replies
Yannick
Yannick•5mo ago
You can get the request event with getRequestEvent(); on the client
AlberTenez
AlberTenez•5mo ago
Let me try that, thanks! 🙂