Skip to content
This repository was archived by the owner on Jan 11, 2023. It is now read-only.

Do not resolve session for static assets #999

Open
imbolc opened this issue Nov 22, 2019 · 2 comments
Open

Do not resolve session for static assets #999

imbolc opened this issue Nov 22, 2019 · 2 comments

Comments

@imbolc
Copy link

imbolc commented Nov 22, 2019

I fetch current session from backend and then pass it into sapper.middleware:

async function load_session(rq, res, next) {
    console.log(rq.url)
    const origin = rq.protocol + "://" + rq.get("host")
    let data = {}
    try {
        let r = await fetch(origin + "/api/session", {
            headers: { cookie: rq.headers.cookie },
        })
        data = await r.json()
    } catch (e) {
        console.error(e)
    }
    rq._sapper_session = data  // eslint-disable-line require-atomic-updates
    next()
}

app.use(
    sirv("static", { dev }),
    load_session,
    sapper.middleware({
        session: rq => rq._sapper_session,
    }),
)

I use load_session as middleware because sapper.middleware isn't awaitable

But major issue I found is that session is also requested for each static asset:

/client/app.b8f542ed.js
INFO:     127.0.0.1:52014 - "GET /api/session HTTP/1.1" 200 OK
/client/sapper-dev-client.89e34bae.js
INFO:     127.0.0.1:52018 - "GET /api/session HTTP/1.1" 200 OK
/client/index.258bbbda.js
INFO:     127.0.0.1:52022 - "GET /api/session HTTP/1.1" 200 OK
/logo-192.png
INFO:     127.0.0.1:52028 - "GET /api/session HTTP/1.1" 200 OK

The way to fix coming up to my mind is make session.middleware to consume a promise and then resolve it only when we actually need the session.

@bcharbonnier
Copy link

Actually I had the kind of same realisation on my project, and I discovered that files coming from client/ are actually served by sapper.middleware.

You can safely (or maybe I missed something) serve them before going through sapper.middleware.

If you are using express, you can do this

app.use(
    sirv("static", { dev })
)
.use("/client", .use("/client", sirv(`__sapper__/${dev ? "dev" : "build"}/client`, { dev })))
.use(
    load_session,
    sapper.middleware({
        session: rq => rq._sapper_session,
    }),
)

If you are using polka, it won't work (have a look here to understand why)

For /logo-192.png it is weird as it should be served by the first sirv("static", { dev })

@petergarnaes
Copy link

I would just like to add that I have issues with session middleware being applied to static .js assets as well. My server handles sessions by itself, but because the middleware is applied on all the static .js assets it becomes very slow when loading the site from a clean tab.

The fix provided by @bcharbonnier works, but does not seem idiomatic to me.

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants