diff --git a/.github/workflows/test.yaml b/.github/workflows/test.yaml index 59ff83951..f3a3496f0 100644 --- a/.github/workflows/test.yaml +++ b/.github/workflows/test.yaml @@ -14,7 +14,7 @@ jobs: NEXT_PUBLIC_VERCEL_URL: nitric.io steps: - name: Checkout - uses: actions/checkout@v2 + uses: actions/checkout@v3 - uses: actions/setup-node@v3 with: node-version: 18 @@ -27,33 +27,13 @@ jobs: run: yarn format:check - name: Run spellcheck test run: yarn test:spellcheck - - name: Build Website - run: yarn build - env: - NEXT_PUBLIC_GITHUB_BRANCH: ${{ github.head_ref || github.ref_name }} - - name: Cache Build - uses: actions/cache@v2 - id: restore-build - with: - path: | - .next - public - key: ci-docs-test-${{ github.sha }} test-broken-links: runs-on: ubuntu-latest needs: [tests] steps: - name: Checkout - uses: actions/checkout@v2 - - name: Restore Build - uses: actions/cache@v2 - id: restore-build - with: - path: | - .next - public - key: ci-docs-test-${{ github.sha }} + uses: actions/checkout@v3 - name: Cypress tests 🧪 uses: cypress-io/github-action@v5 with: @@ -61,9 +41,11 @@ jobs: config: video=false browser: chrome spec: cypress/e2e/broken-links.cy.ts - build: node scripts/build-pages-fixture.js + build: yarn cypress:build start: yarn start wait-on: 'http://localhost:3000' + env: + NEXT_PUBLIC_GITHUB_BRANCH: ${{ github.head_ref || github.ref_name }} - name: Upload screenshots uses: actions/upload-artifact@v4 if: failure() @@ -76,15 +58,7 @@ jobs: needs: [tests] steps: - name: Checkout - uses: actions/checkout@v2 - - name: Restore Build - uses: actions/cache@v2 - id: restore-build - with: - path: | - .next - public - key: ci-docs-test-${{ github.sha }} + uses: actions/checkout@v3 - name: Cypress tests 🧪 uses: cypress-io/github-action@v5 with: @@ -92,9 +66,11 @@ jobs: config: video=false browser: chrome spec: cypress/e2e/a11y.cy.ts - build: node scripts/build-pages-fixture.js + build: yarn cypress:build start: yarn start wait-on: 'http://localhost:3000' + env: + NEXT_PUBLIC_GITHUB_BRANCH: ${{ github.head_ref || github.ref_name }} - name: Upload screenshots uses: actions/upload-artifact@v4 if: failure() @@ -107,15 +83,7 @@ jobs: needs: [tests] steps: - name: Checkout - uses: actions/checkout@v2 - - name: Restore Build - uses: actions/cache@v2 - id: restore-build - with: - path: | - .next - public - key: ci-docs-test-${{ github.sha }} + uses: actions/checkout@v3 - name: Cypress tests 🧪 uses: cypress-io/github-action@v5 with: @@ -123,9 +91,11 @@ jobs: config: video=false browser: chrome spec: cypress/e2e/seo.cy.ts - build: node scripts/build-pages-fixture.js + build: yarn cypress:build start: yarn start wait-on: 'http://localhost:3000' + env: + NEXT_PUBLIC_GITHUB_BRANCH: ${{ github.head_ref || github.ref_name }} - name: Upload screenshots uses: actions/upload-artifact@v4 if: failure() diff --git a/.gitignore b/.gitignore index 55175ef86..60e8169f0 100644 --- a/.gitignore +++ b/.gitignore @@ -23,10 +23,17 @@ npm-debug.log* yarn-debug.log* yarn-error.log* -.pnpm-debug.log* # local env files .env*.local # vercel .vercel + +# typescript +*.tsbuildinfo +next-env.d.ts + +.contentlayer + +old diff --git a/.husky/pre-commit b/.husky/pre-commit new file mode 100644 index 000000000..372362317 --- /dev/null +++ b/.husky/pre-commit @@ -0,0 +1 @@ +yarn lint-staged diff --git a/.spellcheckerrc.yml b/.spellcheckerrc.yml index 38ec9f4ac..0ec37d44e 100644 --- a/.spellcheckerrc.yml +++ b/.spellcheckerrc.yml @@ -1,5 +1,5 @@ files: - - 'src/pages/**/*.{md,mdx}' + - 'docs/**/*.{md,mdx}' dictionaries: - dictionary.txt quiet: true diff --git a/components.json b/components.json index f4668fca4..ff2d0f1df 100644 --- a/components.json +++ b/components.json @@ -1,17 +1,20 @@ { "$schema": "https://ui.shadcn.com/schema.json", - "style": "default", - "rsc": false, + "style": "new-york", + "rsc": true, "tsx": true, "tailwind": { - "config": "tailwind.config.js", + "config": "tailwind.config.ts", "css": "src/styles/tailwind.css", - "baseColor": "slate", + "baseColor": "zinc", "cssVariables": true, "prefix": "" }, "aliases": { "components": "@/components", - "utils": "@/lib/utils" + "utils": "@/lib/utils", + "ui": "@/components/ui", + "lib": "@/lib", + "hooks": "@/hooks" } } diff --git a/contentlayer.config.ts b/contentlayer.config.ts new file mode 100644 index 000000000..65a69907a --- /dev/null +++ b/contentlayer.config.ts @@ -0,0 +1,82 @@ +import { defineDocumentType, makeSource } from 'contentlayer2/source-files' +import { extractTocHeadings } from './src/mdx/remark-toc-headings.mjs' +import path from 'path' +import fs from 'fs' + +const contentDirPath = 'docs' + +const branch = process.env.NEXT_PUBLIC_GITHUB_BRANCH || 'main' + +const Doc = defineDocumentType(() => ({ + name: 'Doc', + filePathPattern: '**/*.mdx', + fields: { + title_seo: { + type: 'string', + description: + 'The meta title of the doc, this will override the title extracted from the markdown and the nav title', + }, + description: { + type: 'string', + description: 'The description of the doc', + }, + image: { + type: 'string', + description: 'The image of the doc', + }, + image_alt: { + type: 'string', + description: 'The image alt of the doc', + }, + disable_edit: { + type: 'boolean', + description: 'Disable the github edit button', + }, + tags: { + type: 'list', + of: { + type: 'string', + }, + description: 'The tags of the post, used by guides', + }, + }, + computedFields: { + slug: { + type: 'string', + resolve: (doc) => doc._raw.flattenedPath, + }, + toc: { type: 'json', resolve: (doc) => extractTocHeadings(doc.body.raw) }, + title: { + type: 'string', + resolve: async (doc) => { + const headings = await extractTocHeadings(doc.body.raw, [1]) + + return headings[0]?.value + }, + }, + editUrl: { + type: 'string', + resolve: (doc) => + `https://github.com/nitrictech/docs/edit/${branch}/docs/${doc._raw.sourceFilePath}`, + }, + lastModified: { + type: 'date', + resolve: (doc) => { + // Get the full path to the markdown file + const filePath = path.join( + process.cwd(), + contentDirPath, + doc._raw.sourceFilePath, + ) + // Extract and return the last modified date + const stats = fs.statSync(filePath) + return stats.mtime // This is the last modified date + }, + }, + }, +})) + +export default makeSource({ + contentDirPath, + documentTypes: [Doc], +}) diff --git a/cypress.config.ts b/cypress.config.ts index f343d4a3c..5596210ce 100644 --- a/cypress.config.ts +++ b/cypress.config.ts @@ -4,8 +4,18 @@ export default defineConfig({ e2e: { baseUrl: 'http://localhost:3000', setupNodeEvents(on, config) { - // require("cypress-fail-fast/plugin")(on, config); - return config + on('task', { + log(message) { + console.log(message) + + return null + }, + table(message) { + console.table(message) + + return null + }, + }) }, }, }) diff --git a/cypress/e2e/a11y.cy.ts b/cypress/e2e/a11y.cy.ts index 294b34e98..a5813d410 100644 --- a/cypress/e2e/a11y.cy.ts +++ b/cypress/e2e/a11y.cy.ts @@ -2,17 +2,72 @@ import * as pages from '../fixtures/pages.json' describe('a11y accessiblity test suite', () => { pages.forEach((page) => { - it(`Should test page ${page} for a11y violations`, () => { + it(`Should test page ${page} for a11y violations on desktop`, () => { cy.viewport('macbook-16') cy.visit(page) cy.injectAxe() - cy.wait(150) + cy.wait(500) cy.checkA11y( undefined, { includedImpacts: ['critical'], }, - ); + (violations) => { + cy.task( + 'log', + `${violations.length} accessibility violation${ + violations.length === 1 ? '' : 's' + } ${violations.length === 1 ? 'was' : 'were'} detected`, + ) + // pluck specific keys to keep the table readable + const violationData = violations.map( + ({ id, impact, description, nodes }) => ({ + id, + impact, + description, + nodes: nodes.length, + }), + ) + + cy.task('table', violationData) + + // console.error(JSON.stringify(violations)); + }, + ) + }) + + it(`Should test page ${page} for a11y violations on mobile`, () => { + cy.viewport('iphone-x') + cy.visit(page) + cy.injectAxe() + cy.wait(500) + cy.checkA11y( + undefined, + { + includedImpacts: ['critical'], + }, + (violations) => { + cy.task( + 'log', + `${violations.length} accessibility violation${ + violations.length === 1 ? '' : 's' + } ${violations.length === 1 ? 'was' : 'were'} detected`, + ) + // pluck specific keys to keep the table readable + const violationData = violations.map( + ({ id, impact, description, nodes }) => ({ + id, + impact, + description, + nodes: nodes.length, + }), + ) + + cy.task('table', violationData) + + // console.error(JSON.stringify(violations)); + }, + ) }) }) }) diff --git a/cypress/e2e/broken-links.cy.ts b/cypress/e2e/broken-links.cy.ts index 2ef8f3e21..977aa9dc8 100644 --- a/cypress/e2e/broken-links.cy.ts +++ b/cypress/e2e/broken-links.cy.ts @@ -1,6 +1,5 @@ import * as pages from '../fixtures/pages.json' -import { XMLParser } from 'fast-xml-parser' -const parser = new XMLParser() +import * as prodPages from '../fixtures/prod_pages.json' const CORRECT_CODES = [200] // site should not return internal redirects @@ -33,11 +32,11 @@ const isExternalUrl = (url: string) => { return !url.includes('localhost') } -const req = (url: string, retryCount = 0) => { +const req = (url: string, retryCount = 0, followRedirect = false): any => { return cy .request({ url, - followRedirect: false, + followRedirect, failOnStatusCode: false, gzip: false, }) @@ -71,7 +70,8 @@ describe('Broken links test suite', () => { (link.getAttribute('href') && link.getAttribute('href')?.includes(l)) || //@ts-ignore - (link.getAttribute('src') && link.getAttribute('src').includes(l)) + (link.getAttribute('src') && + link.getAttribute('src').includes(l)), ) }) .each((link) => { @@ -84,13 +84,13 @@ describe('Broken links test suite', () => { cy.log(`link already checked`) expect(VISITED_SUCCESSFUL_LINKS[url]).to.be.true } else { - cy.wait(100) + cy.wait(25) req(url).then((res: Cypress.Response) => { let acceptableCodes = CORRECT_CODES if (REDIRECT_CODES.includes(res.status) && !isExternalUrl(url)) { assert.fail( - `${url} returned ${res.status} to ${res.headers['location']}` + `${url} returned ${res.status} to ${res.headers['location']}`, ) } else { acceptableCodes = [ @@ -106,7 +106,7 @@ describe('Broken links test suite', () => { expect(res.status).oneOf( acceptableCodes, - `${url} returned ${res.status}` + `${url} returned ${res.status}`, ) }) } @@ -116,28 +116,11 @@ describe('Broken links test suite', () => { }) describe('Current links test suite', () => { - let paths: string[] - - beforeEach(() => { - const PROD_BASE_URL = 'https://nitric.io/docs' - - cy.request(`${PROD_BASE_URL}/sitemap-0.xml`).then((response) => { - const jsonObj = parser.parse(response.body, false) - - paths = jsonObj.urlset.url.map((p) => - p.loc === PROD_BASE_URL - ? '/docs' - : `/docs${p.loc - .substring(PROD_BASE_URL.length, p.loc.length) - .replace('/_index', '')}` - ) - }) - }) - - it(`should visit all pages in the current prod sitemap`, function () { - paths.forEach((path) => { - cy.log(`visiting page: ${path}`) - cy.visit(path) + prodPages.forEach((path) => { + it(`should visit page ${path} in the current prod sitemap`, function () { + req(path, 3, true).then((res: Cypress.Response) => { + expect(res.status).to.be.oneOf(CORRECT_CODES) + }) }) }) }) diff --git a/cypress/e2e/seo.cy.ts b/cypress/e2e/seo.cy.ts index c9ed91967..6acb9746c 100644 --- a/cypress/e2e/seo.cy.ts +++ b/cypress/e2e/seo.cy.ts @@ -10,7 +10,11 @@ describe('canonical urls', () => { cy.get('link[rel="canonical"]') .invoke('attr', 'href') - .should('equal', `https://nitric.io${redirects[page] || page}`) + .should('equal', `http://localhost:3000${redirects[page] || page}`) + + cy.get('meta[property="og:url"]') + .invoke('attr', 'content') + .should('equal', `http://localhost:3000${redirects[page] || page}`) }) }) }) diff --git a/dictionary.txt b/dictionary.txt index aaedcd23b..ab5cf9f2b 100644 --- a/dictionary.txt +++ b/dictionary.txt @@ -203,6 +203,19 @@ monorepos decrypts deploytf href +AWSTF +GCPTF +MacOS +GPUs +microservices +misconfigured +CMS +frictionless +ctx +reproducibility +misconfigurations +DSL +UI ^.+[-:_]\w+$ [a-z]+([A-Z0-9]|[A-Z0-9]\w+) diff --git a/docs/apis.mdx b/docs/apis.mdx new file mode 100644 index 000000000..c2ff421b0 --- /dev/null +++ b/docs/apis.mdx @@ -0,0 +1,1279 @@ +--- +description: 'Building HTTP APIs with Nitric' +--- + +# APIs + +Nitric has built-in support for web apps and HTTP API development. The `api` resource allows you to create APIs in your applications, including routing, middleware and request handlers. + +## Creating APIs + +Nitric allows you define named APIs, each with their own routes, middleware, handlers and security. + +Here's an example of how to create a new API with Nitric: + + + +```javascript !! +import { api } from '@nitric/sdk' + +// each API needs a unique name +const galaxyApi = api('far-away-galaxy-api') + +galaxyApi.get('/moon', async ({ req, res }) => { + res.body = "that's no moon, it's a space station." +}) +``` + +```typescript !! +import { api } from '@nitric/sdk' + +// each API needs a unique name +const galaxyApi = api('far-away-galaxy-api') + +galaxyApi.get('/moon', async ({ req, res }) => { + res.body = "that's no moon, it's a space station." +}) +``` + +```python !! +from nitric.resources import api +from nitric.application import Nitric + +# each API needs a unique name +galaxy_api = api('far-away-galaxy-api') + +@galaxy_api.get("/moon") +async def get_moon(ctx): + ctx.res.body = "that's no moon, it's a space station." + +Nitric.run() +``` + +```go !! +package main + +import ( + "github.com/nitrictech/go-sdk/nitric" + "github.com/nitrictech/go-sdk/nitric/apis" +) + +func main() { + galaxyApi := nitric.NewApi("far-away-galaxy-api") + galaxyApi.Get("/moon", func(ctx *apis.Ctx) { + ctx.Response.Body = []byte("that's no moon, it's a space station.") + }) + + nitric.Run() +} +``` + +```dart !! +import 'package:nitric_sdk/nitric.dart'; + +// each API needs a unique name +final galaxyApi = Nitric.api("far-away-galaxy-api"); + +galaxyApi.get("/moon", (ctx) async { + ctx.res.body = "that's no moon, it's a space station."; + + return ctx; +}); +``` + + + +## Routing + +You can define routes and handler services for incoming requests using methods on your API objects. + +For example, you can declare a route that handles `POST` requests using the `post()` method. When declaring routes you provide the path to match and a callback that will serve as the handler for matching requests. + + + Depending on the language SDK, callbacks are either passed as parameters or + defined using decorators. + + + + +```javascript !! +import { getPlanetList, createPlanet } from 'planets' + +galaxyApi.get('/planets', async (ctx) => { + ctx.res.json(getPlanetList()) +}) + +galaxyApi.post('/planets', async (ctx) => { + createPlanet(ctx.req.json()) + ctx.res.status = 201 +}) +``` + +```typescript !! +import { getPlanetList, createPlanet } from 'planets' + +galaxyApi.get('/planets', async (ctx) => { + ctx.res.json(getPlanetList()) +}) + +galaxyApi.post('/planets', async (ctx) => { + createPlanet(ctx.req.json()) + ctx.res.status = 201 +}) +``` + +```python !! +from planets import get_planets_list, create_planet + +@galaxy_api.get("/planets") +async def list_planets(ctx): + ctx.res.body = get_planets_list() + +@galaxy_api.post("/planets") +async def create_planet(ctx): + create_planet(ctx.req.json()) + ctx.res.status = 201 +``` + +```go !! +package main + +import ( + "github.com/nitrictech/go-sdk/nitric" + "github.com/nitrictech/go-sdk/nitric/apis" +) + +func main() { + galaxyApi := nitric.NewApi("far-away-galaxy-api") + + galaxyApi.Get("/planets", func(ctx *apis.Ctx) { + ctx.Response.Headers = map[string][]string{"Content-Type": {"application/json"}} + ctx.Response.Body = []byte(GetPlanetList()) + }) + + galaxyApi.Post("/planets", func(ctx *apis.Ctx) { + CreatePlanet(ctx.Request.Data()) + ctx.Response.Status = 201 + }) + + nitric.Run() +} + +``` + +```dart !! +import 'package:planets' + +galaxyApi.get("/planets", (ctx) async { + ctx.res.json(getPlanetList()); + + return ctx; +}); + +galaxyApi.post("/planets", (ctx) async { + createPlanet(ctx.req.json()); + ctx.res.status = 201; + + return ctx; +}); +``` + + + +### Request Context + +Nitric provides callbacks with a single context object that gives you everything you need to read requests and write responses. By convention this object is typically named `ctx`. + +The context object includes a request `req` and response `res`, which in turn provide convenient methods for reading and writing bodies, as well as auto-extracted parameters and HTTP headers. + +#### Parameters + +The path string used to declare routes can include named parameters. The values collected from those parameters are automatically included in the context object under `ctx.req.params`. + +Path parameters are denoted by a colon prefix `:` + + + +```javascript !! +import { getPlanet } from 'planets' + +// create a dynamic route and extract the parameter `name` +galaxyApi.get('/planets/:name', async (ctx) => { + const { name } = ctx.req.params + ctx.res.json(getPlanet(name)) +}) +``` + +```typescript !! +import { getPlanet } from 'planets' + +// create a dynamic route and extract the parameter `name` +galaxyApi.get('/planets/:name', async (ctx) => { + const { name } = ctx.req.params + ctx.res.json(getPlanet(name)) +}) +``` + +```python !! +from planets import get_planet + +# create a dynamic route and extract the parameter `name` +@galaxy_api.get("/planets/:name") +async def get_planet_route(ctx): + name = ctx.req.params['name'] + ctx.res.body = get_planet(name) +``` + +```go !! +package main + +import ( + "github.com/nitrictech/go-sdk/nitric" + "github.com/nitrictech/go-sdk/nitric/apis" +) + +func main() { + galaxyApi := nitric.NewApi("far-away-galaxy-api") + + // create a dynamic route and extract the parameter `name` + galaxyApi.Get("/planets/:name", func(ctx *apis.Ctx) { + name := ctx.Request.PathParams()["name"] + + ctx.Response.Body = []byte(GetPlanet(name)) + }) + + nitric.Run() +} + +``` + +```dart !! +import 'package:planets' + +// create a dynamic route and extract the parameter `name` +galaxyApi.get("/planets/:name", (ctx) async { + final name = ctx.req.pathParams["name"]!; + + ctx.res.json(getPlanet(name)); + + return ctx; +}); +``` + + + +#### HTTP status and headers + +The response object provides `status` and `headers` properties you can use to return HTTP status codes and headers. + + + +```javascript !! +// return a redirect response using status 301 +galaxyApi.get('/planets/alderaan', async (ctx) => { + ctx.res.status = 301 + ctx.res.headers['Location'] = ['https://example.org/debris/alderaan'] +}) +``` + +```typescript !! +// return a redirect response using status 301 +galaxyApi.get('/planets/alderaan', async (ctx) => { + ctx.res.status = 301 + ctx.res.headers['Location'] = ['https://example.org/debris/alderaan'] +}) +``` + +```python !! +# return a redirect response using status 301 +@galaxy_api.get("/planets/alderaan") +async def find_alderaan(ctx): + ctx.res.status = 301 + ctx.res.headers["Location"] = "https://example.org/debris/alderaan" +``` + +```go !! +// return a redirect response using status 301 +galaxyApi.Get("/planets/alderaan", func(ctx *apis.Ctx) { + ctx.Response.Status = 301 + ctx.Response.Location = "https://example.org/debris/alderaan" +}) +``` + +```dart !! +// return a redirect response using status 301 +galaxyApi.get("/planets/alderaan", (ctx) async { + ctx.res.status = 301; + ctx.res.headers["Location"] = ["https://example.org/debris/alderaan"]; + + return ctx; +}); +``` + + + +## API Security + +APIs can include security definitions for OIDC-compatible providers such as [Auth0](https://auth0.com/), [FusionAuth](https://fusionauth.io/) and [AWS Cognito](https://aws.amazon.com/cognito/). + + + Applying security at the API allows AWS, Google Cloud and Azure to reject + unauthenticated or unauthorized requests at the API Gateway, before invoking + your application code. In serverless environments this reduces costs by + limiting application load from unwanted or malicious requests. + + + + Security rules are currently **not enforced** when using nitric for **local** + development. + + +### Authentication + +APIs can be configured to automatically authenticate and allow or reject incoming requests. A `securityDefinitions` object can be provided, which _defines_ the authentication requirements that can later be enforced by the API. + +The security definition describes the kind of authentication to perform and the configuration required to perform it. For a [JWT](https://jwt.io/) this configuration includes the JWT issuer and audiences. + + + Security definitions only define **available** security requirements for an + API, they don't automatically **apply** those requirements. + + +Once a security definition is available it can be applied to the entire API or selectively to individual routes. + + + +```javascript !! +import { api, oidcRule } from '@nitric/sdk' + +const defaultSecurityRule = oidcRule({ + name: 'default', + audiences: ['https://test-security-definition/'], + issuer: 'https://dev-abc123.us.auth0.com', +}) + +const secureApi = api('main', { + // apply the security definition to all routes in this API. + security: [defaultSecurityRule()], +}) +``` + +```typescript !! +import { api, oidcRule } from '@nitric/sdk' + +const defaultSecurityRule = oidcRule({ + name: 'default', + audiences: ['https://test-security-definition/'], + issuer: 'https://dev-abc123.us.auth0.com', +}) + +const secureApi = api('main', { + // apply the security definition to all routes in this API. + security: [defaultSecurityRule()], +}) +``` + +```python !! +from nitric.resources import api, ApiOptions, oidc_rule +from nitric.application import Nitric + +default_security_rule = oidc_rule( + name="default", + audiences=["https://test-security-definition/"], + issuer="https://dev-abc123.us.auth0.com", +) + +secure_api = api("main", opts=ApiOptions( + # apply the security definition to all routes in this API. + security=[default_security_rule()], + ) +) + +Nitric.run() +``` + +```go !! +package main + +import ( + "github.com/nitrictech/go-sdk/nitric" + "github.com/nitrictech/go-sdk/nitric/apis" +) + +func main() { + defaultSecurityRule := apis.OidcRule( + "default", + "https://dev-abc123.us.auth0.com/.well-known/openid-configuration", + []string{"https://test-security-definition"}, + ) + + secureApi := nitric.NewApi( + "main", + apis.WithSecurity(defaultSecurityRule([]string{})), + ) + + nitric.Run() +} +``` + +```dart !! +import 'package:nitric_sdk/nitric.dart'; + +// define your security definition +final defaultSecurityRule = Nitric.oidcRule( + "default", + "https://dev-abc123.us.auth0.com", + ["https://test-security-definition/"] +); + +final secureApi = Nitric.api( + "main", + opts: ApiOptions( + security: [ + // apply the security definition to all routes in this API. + defaultSecurityRule([]) + ] + ) +); +``` + + + +### Authorization + +In addition to authentication, Nitric APIs can also be configured to perform authorization based on scopes. Again, this can be done at the top level of the API or on individual routes. + +Add the required scopes to the `security` object when applying a security definition. + + + +```javascript !! +import { api, oidcRule } from '@nitric/sdk' + +const defaultSecurityRule = oidcRule({ + name: 'default', + audiences: ['https://test-security-definition/'], + issuer: 'https://dev-abc123.us.auth0.com', +}) + +const secureApi = api('main', { + // apply the security definition to all routes in this API. + // add scopes to the rule to authorize + security: [defaultSecurityRule('user.read')], +}) +``` + +```typescript !! +import { api, oidcRule } from '@nitric/sdk' + +const defaultSecurityRule = oidcRule({ + name: 'default', + audiences: ['https://test-security-definition/'], + issuer: 'https://dev-abc123.us.auth0.com', +}) + +const secureApi = api('main', { + // apply the security definition to all routes in this API. + // add scopes to the rule to authorize + security: [defaultSecurityRule('user.read')], +}) +``` + +```python !! +from nitric.resources import api, ApiOptions, oidc_rule +from nitric.application import Nitric + +default_security_rule = oidc_rule( + name="default", + audiences=["https://test-security-definition/"], + issuer="https://dev-abc123.us.auth0.com", +) + +secure_api = api("main", opts=ApiOptions( + # apply the security definition to all routes in this API. + security=[default_security_rule("user.read")], + ) +) + +Nitric.run() +``` + +```go !! +package main + +import ( + "github.com/nitrictech/go-sdk/nitric" + "github.com/nitrictech/go-sdk/nitric/apis" +) + +func main() { + defaultSecurityRule := apis.OidcRule( + "default", + "https://dev-abc123.us.auth0.com/.well-known/openid-configuration", + []string{"https://test-security-definition/"}, + ) + + secureApi := nitric.NewApi( + "main", + apis.WithSecurity(defaultSecurityRule([]string{"user.read"})), + ) + + nitric.Run() +} + +``` + +```dart !! +import 'package:nitric_sdk/nitric.dart'; + +// define your security definition +final defaultSecurityRule = Nitric.oidcRule( + "default", + "https://dev-abc123.us.auth0.com", + ["https://test-security-definition/"] +); + +final secureApi = Nitric.api( + "main", + opts: ApiOptions( + security: [ + // apply the security definition to all routes in this API. + defaultSecurityRule(["user.read"]) + ] + ) +); +``` + + + +For an in-depth tutorial look at the [Auth0 integration guide](/guides/nodejs/secure-api-auth0) + +### Override API-level security + +Individual routes can have their own security rules which apply any available `securityDefinition`. The requirement defined on routes override any requirements previously set at the top level of the API. + +This allows you to selectively increase or decrease the security requirements for specific routes. + + + +```javascript !! +galaxyApi.get('planets/unsecured-planet', async (ctx) => {}, { + // override top level security to remove security from this route + security: [], +}) + +galaxyApi.post('planets/secured-planet', async (ctx) => {}, { + // override top level security to require user.write scope to access + security: [customSecurityRule('user.write')], +}) +``` + +```typescript !! +galaxyApi.get('planets/unsecured-planet', async (ctx) => {}, { + // override top level security to remove security from this route + security: [], +}) + +galaxyApi.post('planets/secured-planet', async (ctx) => {}, { + // override top level security to require user.write scope to access + security: [customSecurityRule('user.write')], +}) +``` + +```python !! +# override top level security to remove security from this route +@galaxy_api.get("planets/unsecured-planet", opts=MethodOptions(security=[])) +async def get_planet(ctx): + pass + +# override top level security to require user.write scope to access +@galaxy_api.post("planets/secured-planet", opts=MethodOptions(security=[custom_rule("user.write")])) +async def get_planet(ctx): + pass +``` + +```go !! +// override top level security to remove security from this route +secureApi.Get("/planets/unsecured-planet", func(ctx *apis.Ctx) { + // Handle request +}, apis.WithNoMethodSecurity()) + +// override top level security to require user.write scope to access +secureApi.Get("/planets/unsecured-planet", func(ctx *apis.Ctx) { + // Handle request +}, apis.WithSecurity(customRule([]string{"users:write"}))) +``` + +```dart !! +// override top level security to remove security from this route +galaxyApi.get("/planets/unsecured-planet", (ctx) async { + return ctx; +}, security: []); + +// override top level security to require user.write scope to access +galaxyApi.post("/planets/unsecured-planet", (ctx) async { + return ctx; +}, security: [customRule(["user.write"])]); +``` + + + +## Defining Middleware + +Behavior that's common to several APIs or routes can be applied using middleware. Multiple middleware can also be composed to create a cascading set of steps to perform on incoming requests or outgoing responses. + +In most of Nitric's supported languages middleware functions look nearly identical to handlers except for an additional parameter called `next`, which is the next middleware or handler to be called in the chain. By providing each middleware the next middleware in the chain it allows them to intercept requests, response and errors to perform operations like logging, decoration, exception handling and many other common tasks. + + + +```javascript !! +async function validate(ctx, next) { + if (!ctx.req.headers['content-type']) { + ctx.res.status = 400 + ctx.res.body = 'header Content-Type is required' + return ctx + } + return await next(ctx) +} +``` + +```typescript !! +async function validate(ctx, next) { + if (!ctx.req.headers['content-type']) { + ctx.res.status = 400 + ctx.res.body = 'header Content-Type is required' + return ctx + } + return await next(ctx) +} +``` + +```python !! +async def validate(ctx, nxt: HttpMiddleware): + if ctx.req.headers['content-type'] is None: + ctx.res.status = 400 + ctx.res.body = "header Content-Type is required" + return ctx + return await nxt(ctx) +``` + +```go !! +// Using the Go SDK we recommend using higher-order functions to define middleware +func validate(next apis.Handler) apis.Handler { + return func (ctx *apis.Ctx) error { + if ctx.Request.Headers()["content-type"] != nil { + ctx.Response.Status = 400 + ctx.Response.Body = []byte("header Content-Type is required") + + return nil + } + + return next(ctx) + } +} +``` + +```dart !! +// Middleware currently not supported in dart +``` + + + +### API level middleware + +Middleware defined at the API level will be called on every request to every route. + + + +```javascript !! +import { api } from '@nitric/sdk' +import { validate, logRequest } from '../middleware' + +const customersApi = api('customers', { + middleware: [logRequest, validate], +}) +``` + +```typescript !! +import { api } from '@nitric/sdk' +import { validate, logRequest } from '../middleware' + +const customersApi = api('customers', { + middleware: [logRequest, validate], +}) +``` + +```python !! +from nitric.resources import api, ApiOptions +from common.middleware import validate, log_request +from nitric.application import Nitric + +customers_api = api("customers", opts=ApiOptions(middleware=[log_request, validate])) + +Nitric.run() +``` + +```go !! +import ( + "github.com/nitrictech/go-sdk/nitric" + "github.com/nitrictech/go-sdk/nitric/apis" +) + +func validate(next apis.Handler) apis.Handler { + return func(ctx *apis.Ctx) error { + if ctx.Request.Headers()["content-type"] != nil { + ctx.Response.Status = 400 + ctx.Response.Body = []byte("header Content-Type is required") + + return nil + } + + return next(ctx) + } +} + +func main() { + customersApi := nitric.NewApi( + "customers", + apis.WithMiddleware(validate)) + + nitric.Run() +} +``` + +```dart !! +// API level middleware currently not supported in dart +``` + + + +### Route level middleware + +Middleware defined at the route level will only be called for that route. + + + +```javascript !! +import { api } from '@nitric/sdk' +import { validate } from '../middleware' + +const customersApi = api('customers') + +const getAllCustomers = (ctx) => {} + +// Inline using .get() +customersApi.get('/customers', [validate, getAllCustomers]) + +// Using .route() +customersApi.route('/customers').get([validate, getAllCustomers]) +``` + +```typescript !! +import { api } from '@nitric/sdk' +import { validate } from '../middleware' + +const customersApi = api('customers') + +const getAllCustomers = (ctx) => {} + +// Inline using .get() +customersApi.get('/customers', [validate, getAllCustomers]) + +// Using .route() +customersApi.route('/customers').get([validate, getAllCustomers]) +``` + +```python !! +# Route level middleware currently not supported in python +``` + +```go !! +import ( + "github.com/nitrictech/go-sdk/nitric" + "github.com/nitrictech/go-sdk/nitric/apis" +) + +func validate(next apis.Handler) apis.Handler { + return func(ctx *apis.Ctx) error { + if ctx.Request.Headers()["content-type"] != nil { + ctx.Response.Status = 400 + ctx.Response.Body = []byte("header Content-Type is required") + + return nil + } + + return next(ctx) + } +} + +func main() { + customersApi := nitric.NewApi("customers") + + customersApi.Get("/customers", validate(func(ctx *apis.Ctx) error { + // handle request + return nil + })) + + nitric.Run() +} +``` + +```dart !! +// Route level middleware currently not supported in dart +``` + + + +## Custom Domains + +Custom domains are currently only supported for AWS deployments. + +By default APIs deployed by Nitric will be assigned a domain by the target cloud provider. If you would like to deploy APIs with predefined custom domains you can specify the custom domains for each API in your project's stack files. For these domains to be successfully configured you will need to meet the prerequisites defined for each cloud provider below. + + + + + +```yaml title:nitric.prod.yaml +provider: nitric/aws@1.1.0 +region: ap-southeast-2 + +# Add a key for configuring apis +apis: + # Target an API by its nitric name + my-api-name: + # provide domains to be used for the api + domains: + - test.example.com +``` + + + + + +```yaml title:nitric.prod.yaml +# currently unsupported - request support here: https://github.com/nitrictech/nitric/issues +``` + + + + + +```yaml title:nitric.prod.yaml +# currently unsupported - request support here: https://github.com/nitrictech/nitric/issues +``` + + + + + +## Custom Descriptions + +By default, APIs will not be deployed with a description. You can add a description using the following configuration in your stack file. + + + + + +```yaml title:nitric.prod.yaml +provider: nitric/aws@1.12.4 +region: ap-southeast-2 + +# Add a key for configuring apis +apis: + # Target an API by its nitric name + my-api-name: + # provide domains to be used for the api + description: An AWS API +``` + + + + + +```yaml title:nitric.prod.yaml +provider: nitric/azure@1.12.4 +region: Australia East +org: example-org +adminemail: test@example.com + +apis: + # Target an API by its nitric name + my-api-name: + # provide domains to be used for the api + description: An Azure API +``` + + + + + +```yaml title:nitric.prod.yaml +provider: nitric/gcp@1.12.4 +region: australia-southeast1 + +# Add a key for configuring apis +apis: + # Target an API by its nitric name + my-api-name: + # provide domains to be used for the api + description: A GCP API +``` + + + + + +### AWS Custom Domain Prerequisites + +To support custom domains with APIs deployed to AWS your domain (or subdomain) will need to be setup as a [hosted zone](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/hosted-zones-working-with.html) in Route 53. + +The general steps to setup a hosted zone in Route 53 are as follows: + +- Navigate to Route 53 in the AWS Console +- Select 'hosted zones' from the left navigation +- Click 'Create hosted zone' +- Enter your domain name and choose the 'Public hosted zone' type. +- Click 'Create hosted zone' +- You will now be provided with a set of NS DNS records to configure in the DNS provider for your domain +- Create the required DNS records, then wait for the DNS changes to propagate + +Once this is done you will be able to use the hosted zone domain or any direct subdomain with your Nitric APIs. + +You can read more about how AWS suggests configuring hosted zones in their documentation on [Making Route 53 the DNS service for a domain that's in use](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/migrate-dns-domain-in-use.html) or [Making Route 53 the DNS service for an inactive domain](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/migrate-dns-domain-inactive.html) + + + If the hosted zone was `nitric.io`, `nitric.io` or `api.nitric.io` would be + supported for APIs, but not `public.api.nitric.io` since that is a subdomain + of a subdomain. + + + + DNS propagation of the NS records can take a few seconds to a few hours due to + the nature of DNS. + + +If you're more of a visual learner, below is a video that walks through how to set up your custom domains. + +
+
+