hyte-web-dev

Getting started with server-side development

Architecture and concepts

Typical client-server architecture in web applications

graph TD

subgraph "Client (browser)"
   DOM[HTML/CSS user interface, DOM] -- events --> CSL["Client-side Logic (JavaScript)"]
   CSL -- DOM manipulation --> DOM
end

subgraph "Web server"
   SSL[Server-side Logic]
   SFS[Static file server]
end

subgraph DBMS
   DB[(Database)]
end

DOM -- HTTP GET --> SFS
SFS -- assets --> DOM
CSL -- HTTP CRUD requests --> SSL
SSL -- HTTP responses (JSON) --> CSL
SSL <-- SQL--> DB
  1. The client, which can be a user’s device (e.g., computer or smartphone) with a web browser, connects to the server over the internet.
    • The Hypertext Transfer Protocol (HTTP) is commonly used for communication between the client and server.
  2. Web browser (the Client) loads HTML, CSS, JavaScript, images and other static UI files from the server using HTTP GET requests.
  3. The user interacts with the user interface on the client side.
  4. Based on the interaction, the Client-side Logic prepares a request to send to the server.
  5. The request for a resource is sent to the Server.
    • Requests can be of various types, such as GET, POST, PUT, DELETE, etc., depending on the action being performed.
    • Resources are identified using URLs (Uniform Resource Locators).
  6. On the server side, the server-side logic processes the request. This may involve querying a database or performing other operations.
    • Web applications store and retrieve data using databases like MySQL, PostgreSQL, or MongoDB.
    • Back-end code interacts with the database to perform operations like storing, updating, and retrieving information.
  7. The server generates a response and sends it back to the client. The response can be in the form of HTML, CSS, JavaScript, or data in other formats like JSON or XML.
  8. The client (JavaScript code run by the browser) processes the response, updating the User Interface or performing other actions as necessary. This mechanism is often referred to as “Client-Side Rendering”.
  9. Users continue to interact with the web application and trigger new HTTP requests, which the server processes to provide the desired data.
    • Users interact with the web application by performing actions like clicking buttons or submitting forms.
    • These interactions trigger new requests from the client to the server, creating a continuous cycle of interaction.
sequenceDiagram
    participant browser
    participant server as server-side app
    participant db as database

    browser->>server: GET https://app.example.com/
    activate server
    server-->>browser: (200 OK) HTML document
    deactivate server

    browser->>server: GET https://app.example.com/app.js
    activate server
    server-->>browser: the JavaScript file
    deactivate server

    activate browser
    Note right of browser: The browser starts executing the JS code that fetches some data from the server

    browser->>server: GET https://app.example.com/endpoint/resource
    deactivate browser
    activate server
    server->>db: SQL query
    activate db
    db-->>server: result set
    deactivate db
    server-->>browser: [{ "content": "Hello world!", "date": "2023-1-1" }, ... ]
    deactivate server

    Note right of browser: The browser executes the callback function that renders the notes

HTTP request

HTTP request

POST /index.html HTTP/1.1
Host: example.com
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36
Accept: text/html,application/xhtml+xml
Accept-Language: en-US,en;q=0.9
Content-Type: application/json

{"username": "frank", "password": "12345"}

HTTP methods

Common HTTP request methods include:


HTTP response

HTTP response

HTTP/1.1 200 OK
Server: Apache/2.4.41 (Unix)
Content-Type: text/html
Content-Length: 1234
Date: Sat, 10 Jun 2023 15:30:00 GMT

<!DOCTYPE html>
<html>
<head>
  <title>Example Website</title>
</head>
<body>
  <h1>Welcome to the Example Website!</h1>
  <p>This is the content of the index.html file.</p>
</body>
</html>

HTTP response with an image (or any binary file)

HTTP/1.1 200 OK
Server: Apache/2.4.41 (Unix)
Content-Type: image/jpeg
Content-Length: 12345
Date: Sat, 10 Jun 2023 15:30:00 GMT

[Binary data representing the JPG image]

Status codes

HTTP status codes are issued by a server in response to a client’s request made to the server. They help the client understand the result of their request. Status codes are grouped into five classes:

More information on HTTP status code in the Mozilla Developer Network documentation.

REST

Representational State Transfer, is an architectural style for designing distributed systems. REST is often used in the context of web services, especially when building APIs. RESTful architecture is based on HTTP protocol. In this course we build a REST interface for client-server communication.

Common principles of RESTful architecture:

REST APIs are popular due to their simplicity, scalability, and performance. When an API adheres to these principles, it’s often referred to as a “RESTful” API.

Server-side technologies

Programming language + application framework + database + runtime environment (server) = server-side (back-end) application

JavaScript and Node.js


Tools and Development Environment

Code editor or IDE

Ultimately, it’s your choice. VSCode is used by the teachers.

Visual Studio Code (VSCode)

Install Extensions: Press ctrl-shift-x or click extensions icon on the left panel. Search and install:

Basic Usage

Active project is the folder open on the left side panel (File -> Open folder…)

Handy keyboard shortcuts (finnish layout, check File -> Preferences -> Keyboard shortcuts for more)

Operating system terminal (command line)

Node.js

Install latest Node.js LTS version

Usage, running a javascript file locally without a web browser:

node my-script.js

npm

Other tools needed


Formatting and Linting

Formatters

Linters

Both formatters and linters contribute to maintaining code quality and consistency, but they focus on different aspects of the development process. Formatters primarily deal with code formatting and style, while linters primarily focus on code analysis and identifying potential issues.

EditorConfig

# sample .editorconfig

# Top-most EditorConfig file
root = true

# File encoding
[*]
charset = utf-8

# Indentation settings
[*.{js,mjs}]
indent_style = space
indent_size = 2

[*.css]
indent_style = space
indent_size = 2

[*.html]
indent_style = space
indent_size = 2

# Line endings
[*]
end_of_line = lf

# Trailing whitespace
[*]
trim_trailing_whitespace = true

# New line at the end of the file
[*]
insert_final_newline = true

# Maximum line length
[*.{js,mjs,css,html}]
max_line_length = 80

Prettier

// sample .prettierrc.json 
{
  "semi": true,
  "singleQuote": true,
  "bracketSpacing": false,
  "trailingComma": "es5"
}

ESLint


Setting up front-end (client) web development environment using Vite

Vite

  1. Create a new project with Vite in terminal

    # cd to your code folder
    npm create vite@latest
    # 1. type your project name
    # 2. Select a framework: -> Vanilla
    # 3. Select a variant: -> Javascript
    cd <project-name>
    npm install
    # start vite dev server
    npm run dev
    
  2. Open the preview URL (http://localhost:5173/) in your browser and open developer tools (e.g. Chrome & Chrome DevTools)
  3. Open the project folder in VS Code
  4. To get started with a clean web app template:
    • edit or replace index.html file but do not remove <script type="module" src="/main.js"></script>
    • edit or replace style.css with your own styles
    • edit main.js file (note that the css file is imported in the js file instead of the html file import './style.css';). Everything else boilerplate code can be removed from the js file.
    • remove counter.js and image files because they are just examples

Publishing the website created with Vite

  1. Stop the dev server (ctrl-c) if running
  2. Build the application npm run build

    • If you have more html files than just index.html, you need to add them to configurarion. Create a file called vite.config.js into your project’s root folder:
     // vite.config.js
     import {resolve} from 'path';
     import {defineConfig} from 'vite';
    
     export default defineConfig({
       build: {
         rollupOptions: {
           input: {
             // List your html files here, e.g:
             main: resolve(__dirname, 'index.html'),
             home: resolve(__dirname, 'home.html'),
           },
         },
       },
       // Public base path could be set here too:
       // base: '/~username/my-app/',
     });
    
    • If you are using web server’s root URL (like https://example.com/) as your website address this works out of the box
    • If you are using a subfolder (like https://users.metropolia.fi/~username/my-app/), you need to set a public base path for the app before building.
      • Modify your build script in package.json: "build": "vite build --base=/~username/my-app/", or add the base path to the vite.config.js (see example above).
      • Remember to run npm run build again after updating the config
  3. Copy all contents of dist/ folder to the web server’s public folder

Code style and best practices

Remember that following good coding practices makes your app a lot more easier to maintain, develop and understand:

Preferred coding conventions in this course:

Some generic coding tips: