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:
- For pages and routes: Use .astro files under the
src/pages
directory to create your website’s pages and define routes. - For components: Create reusable UI components using .astro files. These can be imported and used in other .astro files.
- For layouts: Define page layouts using .astro files, which can be shared across multiple pages for consistent structure.
- When you need templating: .astro files support a special JSX-like syntax for templating, making it easy to mix HTML with dynamic content.
When to use .ts files:
- For utility functions: Create .ts files to define reusable functions that can be imported and used across your project.
- For API endpoints: Under
src/pages/api
, use .ts files to create serverless functions that handle HTTP requests. - For type definitions: Define custom types and interfaces in .ts files to enhance type safety in your project.
- For non-UI logic: When you need to write complex logic that doesn’t directly involve rendering HTML, .ts files are often more suitable.
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