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.


download all my books for free

  • javascript handbook
  • typescript handbook
  • css handbook
  • node.js handbook
  • astro handbook
  • html handbook
  • next.js pages router handbook
  • alpine.js handbook
  • htmx handbook
  • react handbook
  • sql handbook
  • git cheat sheet
  • laravel handbook
  • express handbook
  • swift handbook
  • go handbook
  • php handbook
  • python handbook
  • cli handbook
  • c handbook

subscribe to my newsletter to get them

Terms: by subscribing to the newsletter you agree the following terms and conditions and privacy policy. The aim of the newsletter is to keep you up to date about new tutorials, new book releases or courses organized by Flavio. If you wish to unsubscribe from the newsletter, you can click the unsubscribe link that's present at the bottom of each email, anytime. I will not communicate/spread/publish or otherwise give away your address. Your email address is the only personal information collected, and it's only collected for the primary purpose of keeping you informed through the newsletter. It's stored in a secure server based in the EU. You can contact Flavio by emailing flavio@flaviocopes.com. These terms and conditions are governed by the laws in force in Italy and you unconditionally submit to the jurisdiction of the courts of Italy.

Related posts about astro: