Explore 1.5M+ audiobooks & ebooks free for days

Only $12.99 CAD/month after trial. Cancel anytime.

Full-Stack Web Development with TypeScript 5: Craft modern full-stack projects with Bun, PostgreSQL, Svelte, TypeScript, and OpenAI
Full-Stack Web Development with TypeScript 5: Craft modern full-stack projects with Bun, PostgreSQL, Svelte, TypeScript, and OpenAI
Full-Stack Web Development with TypeScript 5: Craft modern full-stack projects with Bun, PostgreSQL, Svelte, TypeScript, and OpenAI
Ebook609 pages3 hours

Full-Stack Web Development with TypeScript 5: Craft modern full-stack projects with Bun, PostgreSQL, Svelte, TypeScript, and OpenAI

Rating: 0 out of 5 stars

()

Read preview
LanguageEnglish
PublisherPackt Publishing
Release dateAug 2, 2024
ISBN9781835885598
Full-Stack Web Development with TypeScript 5: Craft modern full-stack projects with Bun, PostgreSQL, Svelte, TypeScript, and OpenAI

Related to Full-Stack Web Development with TypeScript 5

Related ebooks

Internet & Web For You

View More

Reviews for Full-Stack Web Development with TypeScript 5

Rating: 0 out of 5 stars
0 ratings

0 ratings0 reviews

What did you think?

Tap to rate

Review must be at least 10 words

    Book preview

    Full-Stack Web Development with TypeScript 5 - Mykyta Chernenko

    Cover.png

    Full-Stack Web Development with TypeScript 5

    Copyright © 2024 Packt Publishing

    All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.

    The author acknowledges the use of cutting-edge AI, such as ChatGPT, with the sole aim of enhancing the language and clarity within the book, thereby ensuring a smooth reading experience for readers. It’s important to note that the content itself has been crafted by the author and edited by a professional publishing team.

    Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book.

    Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

    Group Product Manager: Kaustubh Manglurkar

    Publishing Product Manager: Bhavya Rao

    Book Project Manager: Sonam Pandey

    Senior Editor: Rashi Dubey

    Technical Editor: K Bimala Singha

    Copy Editor: Safis Editing

    Indexer: Subalakshmi Govindhan

    Production Designer: Vijay Kamble

    DevRel Marketing Coordinator: Nivedita Pandey and Anamika Singh

    First published: August 2024

    Production reference: 1020724

    Published by Packt Publishing Ltd.

    Grosvenor House

    11 St Paul’s Square

    Birmingham

    B3 1RB, UK

    ISBN 978-1-83588-558-1

    www.packtpub.com

    To my parents, Iryna and Vadym Chernenko; my aunt, Oksana Pidvalna; and my grandparents, Vira and Vasyl Pivdalni, for dedicating everything they could to help me reach where I am now, providing motivation and believing in me. To my wife, Yuliia, for her constant support, encouragement, and tremendous love throughout our life-long journey.

    – Mykyta Chernenko

    Foreword

    In the ever-evolving landscape of web development, mastering the latest technologies and integrating them seamlessly into full-stack projects is not just an advantage; it’s a necessity. Having worked alongside Mykyta Chernenko in various capacities—from frontline coding at Quantum to collaborating on a startup idea—I have witnessed firsthand his deep technical expertise and innovative approach to problem-solving in the tech world.

    Full-Stack Web Development with TypeScript 5 is Mykyta’s latest endeavor to empower full-stack developers by sharing his wealth of knowledge. This book is a beacon for junior and mid-level software engineers who are eager to dive deep into the intricacies of modern web development using an array of cutting-edge tools including TypeScript, Bun, PostgreSQL, Svelte, and the pioneering OpenAI API.

    What sets this book apart is not just its comprehensive coverage of both frontend and backend technologies but its practical, project-based approach. Through Mykyta’s guidance, you will not only learn the theoretical aspects of each technology but also aspects of how to apply some of them in real-world scenarios, crafting robust and scalable web applications. The journey from understanding basic concepts to integrating AI features is laid out with clarity and precision, ensuring that every reader comes away with the ability to navigate and innovate within the tech industry.

    As someone who has seen Mykyta’s meticulous approach to both writing and coding, I am confident that this book will serve as a great resource for those looking to make advancements in their careers. Whether it’s leveraging TypeScript’s capabilities to enhance application reliability or integrating AI to create dynamic user experiences, readers will find Full-Stack Web Development with TypeScript 5 an invaluable guide to becoming well-rounded, forward-thinking developers capable of tackling challenges for real business use cases.

    Embark on this learning journey with Mykyta, and equip yourself with the knowledge to not just participate in the future of tech but to shape it.

    Artem Korchunov

    Senior Software Engineer, Pillsorted

    Contributors

    About the author

    Mykyta Chernenko has over seven years of experience in technology, mainly in full-stack development with a focus on Python and TypeScript. He has also worked with Go, Kotlin, and Dart on various projects. His technical contributions include working on the Azure integration for Nutanix’s cluster discovery project and a key engineering role at Factmata, overseeing engineering and infrastructure. Currently, he holds a position as a senior consultant at KodeWorks. In addition to his technical work, Mykyta has mentored over 20 professionals, sharing his knowledge and experience. He is also the author of The Rational Software Engineer and runs a blog with the same name on Hackernoon, where he writes about his insights in the field.

    A big thank you to my best friend, Artem, for working closely with me, offering valuable feedback, and always being there both as a friend and a technical reviewer. I also want to express my gratitude to everyone at Packt Publishing for their professionalism and for making the publishing process seamless and positive. Your efforts have truly shaped this book.

    About the reviewers

    Kawtar Choubari is a software engineer specializing in JavaScript, TypeScript, React, and Next.js. She has been featured at Next.js Conf (2023) and React Conf (2024) with other community members and has spoken at major conferences, such as React Paris and Devoxx; she is passionate about sharing knowledge and making complex topics accessible.

    Also, Kawtar mentors students, guiding their tech careers, creates tech videos part-time, and shares her conference insights in a vlog format on her YouTube channel (under her name). Dedicated to educating, she conducts workshops and actively engages on social media platforms, sharing her expertise and extending her impact with the tech community.

    Kawtar’s work is encapsulated by these three words: engineering, educating, entertaining.

    Artem Korchunov is a product software engineer at Pillsorted, UK, where he blends a strong team-oriented approach with the ability to independently drive projects from inception to completion. Known for his project management and technical expertise in Terraform, AWS, .NET, and Node.js, Artem skillfully manages both the technical and business aspects of his work.

    I am grateful to the team at Pillsorted for their support and the rich, collaborative experiences that drive mutual growth and innovation.

    Joao Rodrigues is a senior typescript engineer at Acrontum Portugal.

    Table of Contents

    Preface

    Part 1: Introduction to TypeScript

    1

    TypeScript Fundamentals

    Technical requirements

    Introduction to TypeScript and its evolution

    Key differences between TypeScript and JavaScript

    The advantages of using TypeScript in modern web development

    Basic syntax of TypeScript

    Simple types

    Interfaces

    Summary

    2

    TypeScript Deep Dive – Typing, Generics, Classes, and Interfaces

    Technical requirements

    Advanced typing techniques

    Narrowing

    null types

    Function types

    Creating types from other types

    Utility types

    Union types

    Type intersections

    Interface and OOP features

    Interfaces

    OOP functionalities

    Generics

    Promises

    Summary

    Part 2: Backend Development with Bun and TypeScript

    3

    Configuring a Backend Environment with Bun and Hono

    Technical requirements

    Introducing Bun

    Introducing Hono

    Setting up the project

    Adding linting and formatting

    Adding middleware

    Handling environment variables

    Discussing the project structure

    Summary

    4

    Building Backend Infrastructure with Bun, Hono, and TypeScript

    Technical requirements

    Implementing in-memory storage

    Defining the interfaces

    Creating database and API types

    In-memory implementation of the interfaces

    Implementing authentication and authorization

    Developing the authentication middleware

    Defining our controllers

    Implementing chat controllers

    Implementing the endpoints

    Combining the endpoints

    Using the index file for calling the function

    Summary

    5

    Improving Reliability – Testing and Validation

    Technical requirements

    Writing validation with Zod

    Adding validation to our authentication endpoints

    Adding validation to our chat endpoints

    Developing tests with Bun

    Writing tests with Bun’s test runner

    Writing tests for our authentication endpoints

    Writing test for our chat endpoints

    Summary

    6

    Advanced Backend Development – Security, Throttling, Caching, and Logging

    Technical requirements

    Managing security aspects

    Adding request throttling

    Writing the middleware

    Implementing the middleware

    Including the middleware in the main app

    Managing the cache

    Writing the cache middleware

    Using the cache middleware in our chat endpoints

    Using logging

    Creating our logger’s configuration

    Adding logger to our caching middleware

    Summary

    Part 3: Integrating PostgreSQL for Data Management

    7

    PostgreSQL Basics, Storage, and Setup

    Technical requirements

    Setting up PostgreSQL in Docker

    What are Docker and Docker Compose?

    What is PostgreSQL?

    Creating a database as a Docker container

    Constructing the database schema

    Defining the database schema

    Creating the database schema

    Writing CRUD SQL operations

    Summary

    8

    Interacting with PostgreSQL Using Libraries

    Technical requirements

    Integrating SQL implementation in the codebase

    Writing a class

    Updating a user

    Incorporating SQL implementation into the main function

    Replacing in-memory data storage with a SQL-based solution

    Testing our SQL integrations to ensure reliability

    Summary

    9

    Interacting with PostgreSQL Using Prisma ORM

    Technical requirements

    Introduction to ORMs and Prisma

    Introducing Prisma – our ORM of choice

    Understanding Prisma Migrate

    Handling migrations using Prisma

    Defining the database schema

    Applying the migration to our database

    Interacting with the database using Prisma

    Defining the Prisma Client class

    Integrating ORM into the main function

    Testing our ORM integration

    Summary

    Part 4: AI Integration with OpenAI API

    10

    Basics of Integrating External APIs with TypeScript and Hono

    Technical requirements

    Introduction to API integration in TypeScript using fetch

    Handling errors and retries

    Validating API correctness

    Summary

    11

    Setting Up and Configuring the OpenAI API for the Backend

    Technical requirements

    Introduction to LLMs and their applications

    Setting up OpenAI API integration

    Integrating the OpenAI API into our backend

    Summary

    Part 5: Frontend Development with Svelte

    12

    Introduction to Svelte for Frontend Development

    Technical requirements

    What is Svelte?

    History of Svelte

    Differentiation from other frameworks

    Learning Svelte fundamentals

    Component composition structure

    Introduction to .svelte file structure

    Reactivity

    Events

    Bindings

    Handling conditionals and iterating arrays

    Props

    Lifecycle

    Stores

    Summary

    13

    Setting Up the Svelte Project

    Technical requirements

    Discussing Vite and SvelteKit

    Setting up the project

    Exploring the project structure

    Vite configuration file

    TypeScript configuration file

    Svelte configuration file

    Configuring package.json

    HTML entry point

    Main file

    Application title

    Summary

    14

    Svelte Chat Application Development

    Technical requirements

    Writing routes for our application

    Handling authentication logic

    Defining the authentication store

    Implementing Login component

    Implementing Register component

    Developing chat logic

    Creating a parent component

    Implementing the Header component

    Creating the Chat component

    Introducing styling

    Writing application-wide styling

    Styling for our Login and Register components

    Styling our header component

    Styling the chat container

    Styling for the chat list

    Styling our chat popup creation component

    Styling for specific chats

    Summary

    15

    Advanced Svelte Techniques

    Technical requirements

    Configuring formatting and linting

    ESLint config file

    Prettier file

    Exploring a11y

    The importance of accessibility

    Accessibility rules and best practices in Svelte

    Fixing accessibility issues in our project

    Setting up i18n

    Introducing testing

    Configuring the Vite file

    Exploring our setup file

    Writing a test for our component

    Further reading

    Summary

    Index

    Other Books You May Enjoy

    Preface

    This book, Full-Stack Web Development with TypeScript 5, takes you on a journey into the robust and versatile world of TypeScript and will enable you to develop modern web applications from the ground up. With a focus on practical, real-world applications, this guide equips you with the necessary tools and techniques to master full-stack development using cutting-edge technologies such as Bun for the backend, Svelte for the frontend, PostgreSQL for database management, and the OpenAI API for AI integration. Whether you’re looking to deepen your existing knowledge or venture into new aspects of web development, this book provides step-by-step instructions and a project-based learning approach that culminates in the creation of a full-featured chat application.

    Who this book is for

    This book is designed for junior to mid-level software engineers who have a basic understanding of JavaScript and web development principles. It is especially beneficial for those looking to enhance their skills in modern web development technologies and application design, focusing on both frontend and backend development with TypeScript.

    What this book covers

    Chapter 1

    , TypeScript Fundamentals, introduces TypeScript, explaining its evolution from JavaScript and highlighting its fundamental syntax. This chapter lays the foundations for understanding how TypeScript enhances web development capabilities.

    Chapter 2

    , TypeScript Deep Dive – Typing, Generics, Classes, and Interfaces, explores advanced TypeScript features such as static typing, generics, and object-oriented programming concepts, which provide the tools we need to write more robust and maintainable code.

    Chapter 3

    , Configuring a Backend Environment with Bun and Hono, guides you through setting up Bun as a modern JavaScript runtime optimized for TypeScript, focusing on configuring the environment to enhance backend development.

    Chapter 4

    , Building Backend Infrastructure with Bun, Hono, and TypeScript, delves into creating a secure and efficient backend using Bun, Hono, and TypeScript, covering topics such as authentication systems, routing, and middleware integration.

    Chapter 5

    , Improving Reliability – Testing and Validation, focuses on ensuring code quality and reliability in backend development, introducing techniques for data validation and testing strategies using Bun and TypeScript.

    Chapter 6

    , Advanced Backend Development – Security, Throttling, Caching, and Logging, covers critical backend aspects such as security measures, caching strategies, and best practices for debugging and logging to build scalable applications.

    Chapter 7

    , PostgreSQL Basics, Storage, and Setup, explores setting up a database using PostgreSQL within a Docker container to ensure reliable data persistence for web applications, detailing installation, schema construction, and CRUD operations.

    Chapter 8

    , Interacting with PostgreSQL Using Libraries, advances our backend infrastructure by incorporating SQL interactions directly into our server code using the pg library. This chapter discusses efficient and secure data handling, connection strategies, and the importance of testing SQL integrations to bolster application reliability.

    Chapter 9

    , Interacting with PostgreSQL Using Prisma ORM, transitions from direct SQL handling to using Object-Relational Mapping (ORM) for database interactions, focusing on using Prisma to streamline CRUD operations and manage schema migrations. This chapter covers how ORM integration can increase productivity, reduce errors, and make code clearer when working with PostgreSQL, as well as efficient migration management and testing ORM interactions.

    Chapter 10

    , Basics of Integrating External APIs with TypeScript and Hono, concludes our backend setup by teaching how to integrate APIs using fetch for robust communications in TypeScript. This chapter focuses on implementing reliable API calls, including error handling, retries, and response validation, to ensure effective and resilient external service interactions.

    Chapter 11

    , Setting Up and Configuring the OpenAI API for the Backend, details the process of integrating the OpenAI API into a TypeScript-based backend, focusing on configuration, security, and practical uses of AI models.

    Chapter 12

    , Introduction to Svelte for Frontend Development, introduces Svelte, a modern framework for building reactive user interfaces, and highlights its key features and benefits over traditional frameworks.

    Chapter 13

    , Setting up the Svelte Project, guides you through setting up a development environment for a Svelte-based application, exploring the configuration files and initial setup with tools such as Vite and SvelteKit.

    Chapter 14

    , Svelte Chat Application Development, walks through the development of a chat application using Svelte, covering frontend aspects such as routing, state management, and UI design.

    Chapter 15

    , Advanced Svelte Techniques, concludes the book with insights into maintaining and optimizing a Svelte and TypeScript application, covering testing, linting, accessibility, and internationalization strategies.

    To get the most out of this book

    Before diving into this book, it is recommended that you have a solid foundation in JavaScript and basic web development concepts. Familiarity with the essentials of both frontend and backend development will help you understand and implement the advanced techniques covered in this guide. This book assumes knowledge of web application structure and design patterns and aims to enhance your skills through practical application and real-world examples.

    If you are using the digital version of this book, we advise you to type the code yourself or access the code from the book’s GitHub repository (a link is available in the next section). Doing so will help you avoid any potential errors related to the copying and pasting of code.

    If you execute the code on Windows, be aware that Bun is in experimental mode and the instructions provided in the terminal must be used in a bash-like environment.

    Download the example code files

    You can download the example code files for this book from GitHub at https://github.com/PacktPublishing/Full-Stack-Web-Development-with-TypeScript-5

    . If there’s an update to the code, it will be updated in the GitHub repository.

    We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/

    . Check them out!

    Conventions used

    There are a number of text conventions used throughout this book.

    Code in text: Indicates code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles. Here is an example: For example, when [] is used in a numerical context, it is coerced to 0, and division of 4 to 0 results in Infinity.

    A block of code is set as follows:

    const numbers: Array = [1, 2]

    const bigNumbers: number[] = [300, 400]

    When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:

    export function createAuthApp(

      userResource: IDatabaseResource,

    ) {

      authApp.post(

        REGISTER_ROUTE,

        

    zValidator(json, registerSchema)

    ,

        async (c) => {

          

    const { email, password, name } = c.req.valid(json);

     

          ...

    Any command-line input or output is written as follows:

    $ npm install -g typescript

    Bold: Indicates a new term, an important word, or words that you see onscreen. For instance, words in menus or dialog boxes appear in bold. Here is an example: Turn on Automatic ESlint config if it was turned off.

    Tips or important notes

    Appear like this.

    Get in touch

    Feedback from our readers is always welcome.

    General feedback: If you have questions about any aspect of this book, email us at [email protected]

    and mention the book title in the subject of your message.

    Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you

    Enjoying the preview?
    Page 1 of 1