Firstly, there was no issue with the config/middleware.ts. The problem was in the plugin.
This does not work:
server/middlewares/redirect.ts
const redirect = async (ctx: any, next: any) => {
console.log('MyMiddleware');
await next();
};
export default redirect;
server/middleware/index.ts
import redirect from './redirect';
export default {
redirect,
};
server/register.ts
import { Strapi } from '@strapi/strapi';
import middleware from './middlewares';
console.log(middleware.redirect) //This is undefined
export default ({ strapi }: { strapi: Strapi }) => {
strapi.server.use(middleware.redirect); //registration fails
};
middleware.redirect is undefined, registration fails.
However, this is functional:
server/register.ts
import { Strapi } from '@strapi/strapi';
export default ({ strapi }: { strapi: Strapi }) => {
strapi.server.use(async (ctx: any, next: any) => {
console.log('MyMiddleware');
await next();
});
};
The way I found, which I don’t know why (or more exactly, I don’t understand why the other way does not work):
server/middlewares/redirect.ts
const redirect = () => async (ctx: any, next: any) => { //Redirect is now a function that returns the middleware.
console.log('MyMiddleware');
await next();
};
export default redirect;
server/middleware/index.ts
import redirect from './redirect';
export default {
redirect,
};
server/register.ts
import { Strapi } from '@strapi/strapi';
import middleware from './middlewares';
console.log(middleware.redirect()) //This is not undefined anymore
export default ({ strapi }: { strapi: Strapi }) => {
strapi.server.use(middleware.redirect()); //I call the function that returns my middleware and that works.
};
Does someone with dark magic experience give an explanation ? ![]()