From 28e433760aedd06fb3cab5f1bd884398aa49c216 Mon Sep 17 00:00:00 2001 From: Iain Collins Date: Wed, 8 Jul 2020 18:21:58 +0100 Subject: [PATCH] Add support for passing appContext to getCsrfToken Requested in #345 getSession() already does this so seems reasonable to support it in getCsrfToken too. --- src/client/index.js | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/src/client/index.js b/src/client/index.js index 2934a3ad8f..e65ba1e083 100644 --- a/src/client/index.js +++ b/src/client/index.js @@ -120,7 +120,12 @@ const getSession = async ({ req, ctx, triggerEvent = true } = {}) => { } // Universal method (client + server) -const getCsrfToken = async ({ req } = {}) => { +const getCsrfToken = async ({ req, ctx } = {}) => { + // If passed 'appContext' via getInitialProps() in _app.js then get the req + // object from ctx and use that for the req value to allow getCsrfToken() to + // work seemlessly in getInitialProps() on server side pages *and* in _app.js. + if (!req && ctx && ctx.req) { req = ctx.req } + const baseUrl = _apiBaseUrl() const fetchOptions = req ? { headers: { cookie: req.headers.cookie } } : {} const data = await _fetchData(`${baseUrl}/csrf`, fetchOptions)