I am trying to use SocketIO between my react front end and strapi backend.
What i have done is the following:
import { Core } from '@strapi/strapi';
export default {
/**
* An asynchronous register function that runs before
* your application is initialized.
*
* This gives you an opportunity to extend code.
*/
register(/* { strapi }: { strapi: Core.Strapi } */) { },
/**
* An asynchronous bootstrap function that runs before
* your application gets started.
*
* This gives you an opportunity to set up your data model,
* run jobs, or perform some special logic.
*/
bootstrap({ strapi }: { strapi: Core.Strapi }) {
let interval: NodeJS.Timeout;
var io = require('socket.io')(strapi.server.httpServer, {
cors: {
origin: "*",
methods: ["GET", "POST"]
}
});
io.use(async (socket, next) => {
try {
//Socket Authentication
const token = socket.handshake.headers.authorization;
if (!token) {
return next(new Error('Authentication error'));
}
console.log("token: ", token);
let result = await strapi.plugins[
'users-permissions'
].services.jwt.verify(token);
//Save the User ID to the socket connection
// socket.user = result.id;
console.log("result: ", result);
next();
} catch (error) {
console.log(error)
}
}).on('connection', function (socket) { });
io.on('connection', function (socket) {
if (interval) clearInterval(interval);
console.log('User connected');
interval = setInterval(() => io.emit('serverTime', { time: new Date().getTime() }), 1000);
socket.on('disconnect', () => {
console.log('user disconnected');
clearInterval(interval);
});
});
strapi.io = io; //This is the code that is not working
},
};
I am following this tutorial: https://strapi.io/blog/how-to-create-a-real-time-bidding-app-using-strapi-v4-vue-and-socket-io
however the error I am getting is:
Property 'io' does not exist on type 'Strapi'.ts(2339)
My Strapi version is: 5.8.1
What am I missing?
Thank you
The issue you have is Typescript error
, meaning you can just use @ts-ignore
or preferable @ts-expect-error
. (e.g. typescript don't know type of something, at compile time but at runtime it exist)
When you do it like this (injection in strapi
object), you also have to extend Core.Strapi
type:
import type { Core } from "@strapi/strapi";
export type StrapiWithIo = Core.Strapi & {
io: any;
}
if you want io
properly typed you can start here
then whenever you have:
export default ({ strapi }: { strapi: StrapiWithIo }) => ({...})