SSR API Cookie设置/删除

时间:2020-02-16 21:21:19

标签: next.js

我可以使用getInitialProps在ssr上传递cookie

req?.headers?.cookie

我可以在api路由中读取它们,如果请求不是使用ssr的,我也可以设置它们

res.setHeader('Set-Cookie', ...)

但是,如果请求来自API解析器中的getInitialProps(SSR),该如何设置/删除它们呢?

// Api handler
const handler = async (req: NextApiRequest, res: NextApiResponse): Promise<void> => {
  console.log(req.headers.cookie) // works on ssr/client

  res.setHeader('Set-Cookie', ['testSSR2=2; path=/; expires=Thu, 01 Jan 2021 00:00:01 GMT;']) // works on client request only

  res.json({ data: 'test' })
}

1 个答案:

答案 0 :(得分:1)

好的,这似乎可行:

如果服务器发出了提取请求,则我们将“ Set-Cookie”标头克隆(经过一些解析)为res标头。

import fetch from 'isomorphic-unfetch'
import { IncomingMessage, ServerResponse } from 'http'

const payload = (body: any, cookies?: any): object => {
  const headers = {
    Accept: 'application/json',
    'Content-Type': 'application/json',
    cookie: cookies || ''
  }

  return {
    method: 'POST',
    headers,
    credentials: 'same-origin',
    body: JSON.stringify(body)
  }
}

type ApiRes<ExpectedData> = Partial<{ data: ExpectedData }>
type AnyObj = { [key: string]: any }

const fetchAPI = <Body = AnyObj, ExpectedData = AnyObj>(
  apiAction: string,
  body: Body,
  req?: IncomingMessage,
  res?: ServerResponse
): Promise<ApiRes<ExpectedData>> => {
  return new Promise((resolve) => {
    fetch(`mysite/api/some`, payload(body, req?.headers?.cookie))
      .then((raw) => {
        if (req && res) {
          const setCookies = raw.headers.get('Set-Cookie')

          if (setCookies !== null) {
            res.setHeader('Set-Cookie', setCookies.split(';, '))
          }
        }

        return raw.json()
      })
      .then((parsed: ApiRes<ExpectedData>) => resolve(parsed))
      .catch((err) => {
        console.log(err)
      })
  })
}