If you're building a non-trivial Sapper app, you likely need access to your current user in your Sapper server routes as well as your components. In this short article I'll show you how to do both, let's go! π
Create a session middleware
Create a normal Express middleware that assigns your session data to req.session
so we can use it in the Sapper middleware:
// src/middlewares/session.ts
export function session() {
return async (req, res, next) => {
// Get your user somehow, maybe via cookies/JWT
const user = await someMethodToGetUser();
req.session = { user }
next();
};
}
Add middleware to your server
In your src/server.js
, add the session middleware right before your sapper.middleware
and pass in the session data to Sapper:
app.use(session());
app.use(sapper.middleware({ session: (req) => req.session }));
Use in your Sapper server routes
Now you can use your session data in your server routes:
// src/routes/api/me
export async function get(req, res) {
res.json(req.session);
}
Now you can ping /api/me
to get the current user session.
Use in your Svelte components
You can also use the session store in your Svelte components:
<script>
import { stores } from "@sapper/app";
const { session } = stores();
</script>
{#if $session.user}
Logged in
{:else}
Logged out
{/if}
Bonus: Typescript support
To support Typescript, create a src/types.d.ts
file and add the following:
interface User {
id: string
email: string
// anything else you need...
}
interface Session {
user?: User
}
declare namespace Express {
export interface Request {
session?: Session;
}
}
π Wrapping up
Thanks for making this far, hope this was helpful! π
Hat tip to @babeard on the Svelte Discord for the suggestion of using a regular middleware to get the data to Sapper sessions.
Thanks for reading! Consider giving this post a β€οΈ, π¦ or π to bookmark it for later. π
Have other tips, ideas, feedback or corrections? Let me know in the comments! πββοΈ
Don't forget to follow me on Dev.to (danawoodman), Twitter (@danawoodman) and/or Github (danawoodman)!
Top comments (4)
Thank you very much for this great tip.
Can you give us some details how do you structure your folders?
Thanks.
I'm pretty much using Sapper defaults. In the article I show the URLs of the modified files. Other than that, it will depend mostly on the type of app I'm building but I'll have a
src/components
for components and then other context specific folders as neededSo you have middlewares in src/middlewares and only server api in src/routes/api/?
For my current project I have a few folders for other code but it's project specific. I prefer to group by "domain". Eg i have a folder for calculations (
src/calculations
) but all that is personal preference.