Advanced
getOrCreateDocAndToken

getOrCreateDocAndToken

getOrCreateDocAndToken is a helper from our Javascript SDK (opens in a new tab) that can ensure a document with the given ID exists, and then returns a client token that can be used to connect to the document.

If a document ID is not provided, getOrCreateDocAndToken will automatically generate a doc and associated docID for you.

Typically, getOrCreateDocAndToken() should be called as part of your auth endpoint implementation. The resulting clientToken should then be returned from the auth endpoint. The client-side YSweetProvider will call this endpoint to get a new client token when the previous one expires.

export async function POST(request: Request) {
  const { docId } = await request.json()
  if (!hasAccessToDoc(docId)) return new Response('Unauthorized', { status: 401 })
  const clientToken = await getOrCreateDocAndToken(CONNECTION_STRING, docId)
  return Response.json(clientToken)
}
💡

Calling getOrCreateDocAndToken is the equivalent of calling createDoc followed by getClientToken.

y-sweet was created by Jamsocket.