Skip to content

Astro, when to use .astro or .ts files

Someone asked me this question:

I’m curious why in some cases (for example under /pages/app/api) we have some files with the .ts extension like settings.ts while all other files are using the astro extension (activities.astro, projects.astro, teams.astro). What’s the guideline?

That’s a good question!

For routes (files under src/pages) in .astro files you can write the final HTML rendered using that special Astro JSX-like templating syntax.

Outside that folder, we can define components in .astro files, which we can import in other .astro files to generate the final HTML .ts files are where we can define functions we can import anywhere, and under src/pages we can use them to define HTTP API endpoints, so we can listen for specific HTTP methods (POST, PUT, DELETE) using a special syntax, which is easier to use than inside .astro files.

In .ts files you can’t use the Astro JSX-like templating syntax.

When to use .astro files:

When to use .ts files:

Remember, .astro files are primarily for components and pages that output HTML, while .ts files are for pure TypeScript code without any templating. This separation allows for a clear distinction between UI components and business logic in your Astro project.

I wrote 17 books to help you become a better developer, download them all at $0 cost by joining my newsletter

JOIN MY CODING BOOTCAMP, an amazing cohort course that will be a huge step up in your coding career - covering React, Next.js - next edition February 2025

Bootcamp 2025

Join the waiting list