Geckos.io supports authentication via HTTP headers and server-side validation.
Client Side:
Pass an authorization string in the geckos() configuration. This string is sent as an Authorization request header.
Server Side:
Provide an authorization async function in the geckos() configuration.
- The function receives
auth (the header string), the request, and the response. - Return an object: This object will be attached to
channel.userData on the client. - Return
true: Authorizes the connection without adding userData. - Return
false: Responds with a 401 Unauthorized error. - Return a number: Responds with that specific HTTP status code (e.g.,
400, 404).
Note: If the client and server are on different domains, you must set cors: { allowAuthorization: true } on the server.
// client.ts
const username = 'Yannick'
const password = '12E45'
const auth = `${username} ${password}`
const channel = geckos({ authorization: auth })
channel.onConnect(error => {
if (error) {
console.error('Status: ', error.status)
return
}
console.log(channel.userData) // Access authenticated data
})
// server.ts
const io: GeckosServer = geckos({
authorization: async (auth, request, response) => {
const token = auth?.split(' ')
const username = token?.[0]
const password = token?.[1]
const user = await database.getByName(username)
if (user?.username === username && user?.password === password)
return { username: user.username, level: user.level, points: user.points }
return false
},
cors: { allowAuthorization: true }
})