DEV Community

Dana Woodman
Dana Woodman

Posted on

6 2

πŸ§‘β€πŸ’» Getting session data in your Sapper server routes and components

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();
  };
}
Enter fullscreen mode Exit fullscreen mode

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 }));
Enter fullscreen mode Exit fullscreen mode

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);
}
Enter fullscreen mode Exit fullscreen mode

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}
Enter fullscreen mode Exit fullscreen mode

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;
  }
}
Enter fullscreen mode Exit fullscreen mode

🏁 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)!

Image of Timescale

πŸš€ pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applicationsβ€”without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read full post β†’

Top comments (4)

Collapse
 
kvetoslavnovak profile image
kvetoslavnovak β€’

Thank you very much for this great tip.
Can you give us some details how do you structure your folders?
Thanks.

Collapse
 
danawoodman profile image
Dana Woodman β€’

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 needed

Collapse
 
kvetoslavnovak profile image
kvetoslavnovak β€’

So you have middlewares in src/middlewares and only server api in src/routes/api/?

Thread Thread
 
danawoodman profile image
Dana Woodman β€’

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.

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs