Skip to content

Instantly share code, notes, and snippets.

@Edlavio
Created April 7, 2025 02:47
Show Gist options
  • Save Edlavio/5cdfd0b76fb5104c57110dd51e42dd8d to your computer and use it in GitHub Desktop.
Save Edlavio/5cdfd0b76fb5104c57110dd51e42dd8d to your computer and use it in GitHub Desktop.
Custom route in Strapi - To get a blog post by slug
// src/api/post/routes/custom-post.ts
module.exports = {
routes: [
{
method: 'GET',
path: '/posts/slug/:slug',
handler: 'post.findOneBySlug',
config: {
policies: [],
middlewares: [],
auth: false,
},
},
],
};
// src/api/post/controllers/custom-post.ts
/**
* post controller
*/
import { factories } from '@strapi/strapi'
export default factories.createCoreController('api::post.post', ({ strapi }) => ({
async findOneBySlug(ctx) {
const { slug } = ctx.params;
const { query } = ctx;
try {
const post = await strapi.db.query('api::post.post').findOne({
where: { slug },
populate: ['image', 'categories'],
...query,
});
if (!post) {
return ctx.notFound(`Post with slug "${slug}" not found`);
}
const sanitizedEntity = await this.sanitizeOutput(post, ctx);
return this.transformResponse(sanitizedEntity);
} catch (err) {
ctx.throw(500, err);
}
},
}));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment