Anyone managed to create a server side protected route?
I'm having a set of routes that need to be accessible only when the user is authenticated.
As per the documentation, I'm trying to create a function that runs on the server.
https://docs.solidjs.com/solid-start/advanced/auth#protected-routes
I guess it will be enough to check if
better-auth.session_token
cookie is set.
But how do I get access to the cookies in the server side running function?
If I try to use auth.api.getSession()
I need to pass headers. And how do I do that too?
I guess, at the end I should fall back to the client-only authentication, but what's the point of the whole server-side thing... :/Auth - SolidDocs
Documentation for SolidJS, the signals-powered UI framework
Solution:Jump to solution
In an API route you use can get it from the request parameter passed in to the method. More generally you can get it anywhere on the server by using solidjs's getRequestEvent(). I will include some sample code below.
5 Replies
Solution
In an API route you use can get it from the request parameter passed in to the method. More generally you can get it anywhere on the server by using solidjs's getRequestEvent(). I will include some sample code below.
Here's the sample code for the API route:
import { type APIEvent } from "@solidjs/start/server";
import { auth } from "~/lib/auth";
export async function GET({request, params}: APIEvent) {
const headers = request.headers;
console.log("recieved headers are:")
headers?.forEach((value, key) => console.log(
const response = await auth.api.signInEmail({ asResponse: true, headers: getRequestEvent()?.request.headers, body: { email: email, password: password } }); if (response.ok) { const event = getRequestEvent(); event?.response.headers.set("set-cookie", response.headers.get("set-cookie") as string); throw redirect("/test"); } else { const result = await response.json(); throw new Error(
${key}: ${value}
));
console.log(" ");
const session = await auth.api.getSession({
headers: headers as Headers,
});
let returnVal: Response | undefined;
if (session === null) {
returnVal = new Response(null, {
status: 401,
statusText: "couldn't get session",
});
} else {
returnVal = new Response(null, {
status: 200,
statusText: String(headers?.get("cookie") as string),
})
}
return returnVal;
};
Heres the code using getRequestEvent which you'll have to use for actions:
import { action } from "@solidjs/router";
import { redirect } from "@solidjs/router";
import { getRequestEvent } from "solid-js/web";
import { auth } from "~/lib/auth";
export const signInAction = action( async (formData: FormData) => {
"use server";
const email = formData.get("email") as string;
const password = formData.get("password") as string;
const response = await auth.api.signInEmail({ asResponse: true, headers: getRequestEvent()?.request.headers, body: { email: email, password: password } }); if (response.ok) { const event = getRequestEvent(); event?.response.headers.set("set-cookie", response.headers.get("set-cookie") as string); throw redirect("/test"); } else { const result = await response.json(); throw new Error(
Error code : ${response.status}, ${result.message}
);
}
});
Keep in mind for this last code I'm experiencing a bug myself currently, but I don't think its related to retrieving the session cookie using getRequestEvent()Ahhh...
const event = getRequestEvent()
was exactly what I was missing. Thank you!
Just out of curiosity - in your example you are basically moving the sign-in action to a server function. Why not just use the authClient in the browser?No problem. Using authClient is definitely an option. My reason for using a server action is that I don't know how to catch and display any potential login errors to the user using authClient. With server actions you can use the useSubmission() hook to get all the info about an action you'll need to keep the user in the loop about what's going on in a convenient way. If your interested in an example, I recently made a simple dummy project to showcase a possible bug I'm experiencing with better-auth that does this. Here is a link to the project: https://github.com/Garrett-Floyd/better_auth_error. Here is a link to the bug report in case I'm doing it wrong and leading you astray lol: https://github.com/better-auth/better-auth/issues/2303
GitHub
Multiple possible bugs associated with page reload (SolidStart and ...
Is this suited for github? Yes, this is suited for github To Reproduce Go to https://github.com/Garrett-Floyd/better_auth_error and read reproduceBugInstructions.txt for a description of the curren...
I'm a bit AFK because of the holidays and I'll take a better look at your example, but for the catching the login errors I do the following using the client: