I'm using Sapper.js to power my application but only using the static content created by running sapper export
.(我正在使用Sapper.js来驱动我的应用程序,但仅使用通过运行sapper export
创建的静态内容。)
So there is no server rendering the pages.(因此,没有服务器呈现页面。)
I'm using AWS CloudFront with Lambda@Edge to perform authentication on the user's HttpOnly
cookies whenever they request a page.(我将AWS CloudFront与Lambda @ Edge结合使用,以在用户请求页面时对用户的HttpOnly
cookie执行身份验证。) If the user is authenticated, Lambda will then fetch user data such as the user's profile picture, username, etc and set these values in custom headers/cookies (non HttpOnly) on the pages returned by CloudFront.(如果用户通过了身份验证,则Lambda将获取用户数据,例如用户的个人资料图片,用户名等,并在CloudFront返回的页面上的自定义标头/ cookie(非HttpOnly)中设置这些值。)
These values can be set in either headers or cookies, there are no requirements for either.(可以在标头或cookie中设置这些值,没有任何要求。)
But I need to have this dynamic content available to the client before the page is rendered in order to avoid an ugly flash of empty content.(但是我需要在呈现页面之前将动态内容提供给客户端,以避免丑陋的空白内容出现。) So it should be retrieved inside of sapper's preload
function instead of onMount
in order to stall any other html from being rendered until the data is returned.(因此,应在onMount
的preload
函数内部而不是onMount
内检索它,以阻止其他任何html呈现,直到返回数据为止。)
I know how to fetch inside of the preload
function like so:(我知道如何在preload
函数内部获取内容,如下所示:)
<script context="module">
export async function preload(page, session) {
const res = await this.fetch("SOME_ENDPOINT");
const data = await res.json();
return {data};
}
</script>
but I'm not sure on how to get access to headers or cookies from within this function.(但我不确定如何从此函数中访问标题或cookie。)
EDIT: NEW APPROACH?(编辑:新方法?)
So I've been thinking and it seems like the best way to go at this point is to try and transform Sapper's sapper.middleware
function so that it accepts a custom req
object and returns the res
object instead of trying to serve it to the client.(因此,我一直在思考,似乎最好的方法是尝试转换Sapper的sapper.middleware
函数,使其接受自定义的req
对象并返回res
对象,而不是尝试将其提供给客户端。)
Then we can run npm run build
and use the entire build
directory inside of Lambda.(然后,我们可以运行npm run build
并使用Lambda内部的整个build
目录。) We're free to pass any user data into the middleware session
obbject afterwards as it explains in the docs:(之后,我们可以随意将任何用户数据传递到中间件session
,如文档中所述:)
sapper.middleware({session: (CUSTOM_REQ, CUSTOM_RES) => ({user: CUSTOME_REQ.user})})
No need to fetch any data as it should now be available in the store
.(无需获取任何数据,因为它现在应该在store
可用。)
Any thoughts?(有什么想法吗?)
ask by mrstack999 translate from so
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…