FeathersJS
repository·dove·Indexed 12 days ago
https://github.com/feathersjs/feathersA full-stack framework for building web APIs and real-time applications using TypeScript or JavaScript. Feathers is backend-agnostic, supporting various databases and frontend frameworks like React, Vue, and Angular. It provides a comprehensive ecosystem including a CLI, authentication plugins, and multiple transport layers such as REST and Socket.io.
What's inside Feathers
- Feathers is organized into several functional modules that allow you to build real-time applications. The API is categorized into Core functionality, Transports for exposing the API, Authentication mechanisms, Client-side usage, Schema validation, and Database adapters.
Explore the FeathersJS Ecosystem
doveThe FeathersJS ecosystem consists of a variety of official and community-contributed packages designed to extend the functionality of your application. You can find a curated list of these packages, including authentication providers, adapters, and client-side utilities, in the Awesome Packages section of the documentation.Authentication Overview in FeathersJS
doveFeathersJS authentication is provided through a collection of plugins that support various mechanisms including username/password, JWT, and OAuth (e.g., GitHub, Facebook).
It is important to note that
@feathersjs/authenticationis an abstraction layer for authentication mechanisms. It does not handle user management tasks such as user verification or password reset functionality. These must be implemented manually or via external tools likefeathers-authentication-managementor Auth0.What's New in Feathers v5 (Dove)
doveFeathers Dove (v5) is a major release focused on deep TypeScript integration, schema-driven development, and improved performance. Key improvements include:
- Complete TypeScript Rewrite: The entire core, including adapters, hooks, and utilities, is written in TypeScript.
- Typed Client: The CLI generates shared types for both the server and the client, allowing for end-to-end type safety.
- Framework Agnostic API: Supports the Feathers client (isomorphic), KoaJS transport, and ExpressJS transport.
- High-Performance Routing: Includes a built-in Radix Trie router for lightning-fast request routing.
- Official Schemas: Introduces
@feathersjs/schemafor JSON Schema-based validation and automatic TypeScript type generation. - Resolvers: A new way to handle data population and manipulation using specialized hook utilities.
Compare Feathers and Meteor for real-time development
doveWhen choosing between Feathers and Meteor, consider the following architectural and ecosystem differences:
Real-time Transports
- Feathers: Allows you to choose your transport via Socket.io or Primus.
- Meteor: Relies on SockJS.
Database and Ecosystem
- Feathers: Supports a wide variety of databases and integrates with any front-end framework or view engine. It uses npm as its package manager, providing access to the entire npm ecosystem, and allows you to use any build tool (e.g., Webpack, Gulp, Browserify).
- Meteor: Has official support primarily for MongoDB (with some community modules for others). It uses its own package manager, build system, and the Blaze template engine.
Authentication
- Feathers: Uses JSON Web Tokens (JWT) to maintain a stateless authentication state. Supports email/password and OAuth.
- Meteor: Uses sessions to maintain logged-in state. Supports email/password and OAuth.
Real-time Scaling (Clustering)
- Feathers: Handles real-time communication at the service layer or via a pub-sub service like Redis.
- Meteor: Relies on monitoring MongoDB operation logs (oplog tailing) as the central hub for real-time communication.
UI Rendering
- Meteor: Provides built-in optimistic UI rendering.
- Feathers: Leaves optimistic UI implementation to the developer, though it leverages websockets for efficient data flow to minimize the need for complex data diffing.
What is @feathersjs/adapter-tests?
doveThe@feathersjs/adapter-testspackage provides a shared test suite designed to validate that database adapters adhere to the common Feathers database adapter syntax. If you are developing a new database adapter for Feathers, you can use this suite to ensure your implementation is compatible with the expected API and behavior.What is an authentication strategy and how to implement one
doveAn authentication strategy is an object or class used by the
AuthenticationServiceto validate requests. To be compatible, a strategy must implement at least theauthenticate(authentication, params)method.Core Requirements
authenticate(authentication, params): This is the primary method. It takes authentication data and additional parameters. It must either return an authentication result object on success or throw aNotAuthenticatederror on failure.
Optional Methods
Strategies can optionally implement these methods to integrate more deeply with the Feathers application:
setName(name): Sets the name used to register the strategy on the authentication service.setApplication(app): Receives the Feathers application instance.setAuthentication(service): Receives theAuthenticationServiceinstance.verifyConfiguration(): A synchronous method to validate that required configuration fields are present; should throw an error if configuration is invalid.parse(req, res): Parses a plain Node HTTP request/response to extract authentication information. Returnsnullif no information is found.
Built-in Strategies
Feathers provides several ready-to-use strategies:
JWTStrategy(via@feathersjs/authentication)LocalStrategy(via@feathersjs/authentication-local)OAuthStrategy(via@feathersjs/authentication-oauth)
// Minimal implementation requirement class MyCustomStrategy { async authenticate(authentication, params) { // logic to validate authentication // return result object or throw NotAuthenticated } }Understand the role of src/app.ts
doveThesrc/app.tsfile is the central entry point of a Feathers application. It is responsible for initializing the Feathersappobject and wiring it to a specific transport (such as Koa, Express, or Socket.io).Authentication Flows
doveThe Authentication Service supports three primary flows:
1. Creating a new JWT
Users can request a new token by calling
app.service('authentication').create(data)orPOST /authentication. Thedataobject must include the strategy and login credentials:{ strategy: 'local', username: '...', password: '...' }.2. Authenticating an external request
For HTTP requests, the service uses
parseStrategiesto extract authentication data. It calls the strategy's.parsemethod, sets the result inparams.authentication, and then uses theauthenticatehook to verify the credentials and merge the user entity intoparams(e.g.,params.user).3. Authenticating an internal service request
When calling a service internally, you can manually set
params.authentication. Theauthenticatehook will verify this data and merge the resulting entity intoparams.Best Practice: For internal requests where you already have the user object, it is more efficient to set
params.userdirectly instead ofparams.authenticationto avoid the overhead of re-verifying the token.Handle authentication events (login and logout)
doveThe authentication service emits events on the application instance that you can listen to:
app.on('login', (authenticationResult, params, context) => {}): Emitted after a successfulauthService.create()call (e.g., an external login request).- Warning: This event is also sent during WebSocket reconnections; use the
disconnectevent for handling actual disconnections.
- Warning: This event is also sent during WebSocket reconnections; use the
app.on('logout', (authenticationResult, params, context) => {}): Emitted after a successfulauthService.remove()call (an explicit logout).
Event data structure:
authenticationResult: The return value of the service call (usually contains the user and access token).params: The service call parameters.context: The Feathers hook context.
Understand OAuth authentication flows
doveThere are two primary flows for OAuth in Feathers:
1. Browser Redirect (Most Common)
- User visits
http(s)://<host>/oauth/<provider>. - User is redirected to the provider and authorizes the app.
- The provider redirects to the callback path (
/oauth/<provider>/callback). OAuthStrategyretrieves the profile from the server-side Grant response, finds/creates the user, and generates a JWT.- The user is redirected back to the origin with the access token in the URL hash.
- Requirement: Only requires strategy registration and
authentication.oauthconfig. No need to list provider inauthStrategies.
2. Existing Provider Access Token (e.g., Mobile SDKs)
- Client sends a
POST /authenticationrequest with{ strategy: '<provider>', accessToken: '<token>' }. - Requirement: The provider must be listed in
authStrategiesAND you must overridegetProfileto verify the token directly with the provider (e.g., via a UserInfo endpoint). Never trust a client-supplied profile.
- User visits
Explore Feathers Core functionality
doveThe Core module contains the fundamental building blocks that work on both the client and the server:
- Application: The main Feathers application API.
- Services: Service objects, their methods, and Feathers-specific functionality.
- Hooks: Pluggable middleware that can be attached to service methods.
- Events: Events emitted by Feathers service methods.
- Errors: A standardized collection of error classes used throughout the framework.