|
| 1 | +## Build a backend |
| 2 | + |
| 3 | +Next, we will add data and auth capabilities to the app. |
| 4 | + |
| 5 | +### Add data |
| 6 | + |
| 7 | +Each of the `resource.ts` files is where you _define_ the corresponding backend resource. If you open up the `/amplify/data/resource.ts` file in your text editor, you will see some generated code already there: |
| 8 | + |
| 9 | +```ts showLineNumbers title="amplify/data/resource.ts" |
| 10 | +// amplify/data/resource.ts |
| 11 | +import { type ClientSchema, a, defineData } from '@aws-amplify/backend'; |
| 12 | + |
| 13 | +/*== STEP 1 =============================================================== |
| 14 | +The section below creates a Todo database table with a "content" field. Try |
| 15 | +adding a new "isDone" field as a boolean. The authorization rules below |
| 16 | +specify that owners, authenticated via your Auth resource, can "create", |
| 17 | +"read", "update", and "delete" their own records. Public users, |
| 18 | +authenticated via an API key, can only "read" records. |
| 19 | +=========================================================================*/ |
| 20 | +const schema = a.schema({ |
| 21 | + Todo: a |
| 22 | + .model({ |
| 23 | + content: a.string() |
| 24 | + }) |
| 25 | + .authorization([a.allow.owner(), a.allow.public().to(['read'])]) |
| 26 | +}); |
| 27 | + |
| 28 | +export type Schema = ClientSchema<typeof schema>; |
| 29 | + |
| 30 | +export const data = defineData({ |
| 31 | + schema, |
| 32 | + authorizationModes: { |
| 33 | + defaultAuthorizationMode: 'apiKey', |
| 34 | + // API Key is used for a.allow.public() rules |
| 35 | + apiKeyAuthorizationMode: { |
| 36 | + expiresInDays: 30 |
| 37 | + } |
| 38 | + } |
| 39 | +}); |
| 40 | + |
| 41 | +/*== STEP 2 =============================================================== |
| 42 | +Go to your frontend source code. From your client-side code, generate a |
| 43 | +Data client to make CRUDL requests to your table. (THIS SNIPPET WILL ONLY |
| 44 | +WORK IN THE FRONTEND CODE FILE.) |
| 45 | +
|
| 46 | +Using JavaScript or Next.js React Server Components, Middleware, Server |
| 47 | +Actions, or Pages Router? Review how to generate Data clients for those use |
| 48 | +cases: https://docs.amplify.aws/gen2/build-a-backend/data/connect-to-API/ |
| 49 | +=========================================================================*/ |
| 50 | + |
| 51 | +/* |
| 52 | +"use client" |
| 53 | +import { generateClient } from "aws-amplify/data"; |
| 54 | +import { type Schema } from "@/amplify/data/resource"; |
| 55 | +
|
| 56 | +const client = generateClient<Schema>() // use this Data client for CRUDL requests |
| 57 | +*/ |
| 58 | + |
| 59 | +/*== STEP 3 =============================================================== |
| 60 | +Fetch records from the database and use them in your frontend component. |
| 61 | +(THIS SNIPPET WILL ONLY WORK IN THE FRONTEND CODE FILE.) |
| 62 | +=========================================================================*/ |
| 63 | + |
| 64 | +/* For example, in a React component, you can use this snippet in your |
| 65 | + function's RETURN statement */ |
| 66 | +// const { data: todos } = client.models.Todo.list() |
| 67 | + |
| 68 | +// return <ul>{todos.map(todo => <li key={todo.id}>{todo.content}</li>)}</ul> |
| 69 | +``` |
| 70 | + |
| 71 | +<Accordion title='What is a schema?' eyebrow='Learn more'> |
| 72 | + The schema generated by Amplify is for a to-do app. A schema is a blueprint |
| 73 | + for how our app's data will be organized. Within the schema, we will define |
| 74 | + models which will correspond to a database table—`Todo` in the above code. |
| 75 | + Finally, we will define fields which are attributes that each data instance |
| 76 | + will have—in the generated code, the fields are `name` and `description`. Each |
| 77 | + field will have a type attached to it—in the above examples, we are stating |
| 78 | + that both `name` and `description` are strings. |
| 79 | +</Accordion> |
| 80 | + |
| 81 | +Let's make a quick change to our data model and add a `done` field. This will be a `boolean`, which can be set to `true` or `false` depending on whether our to-do list item is complete. Let's also add a priority field, which will be an `enum`. This field type will allow for just a few options to be stored—low, medium, or high. |
| 82 | + |
| 83 | +We've removed the default comments to shorten the code below; however, you can choose to keep them for help in connecting to your frontend resources. |
| 84 | + |
| 85 | +```diff title="amplify/data/resource.ts" |
| 86 | +// amplify/data/resource.ts |
| 87 | +import { type ClientSchema, a, defineData } from '@aws-amplify/backend'; |
| 88 | + |
| 89 | +// ... |
| 90 | + |
| 91 | +const schema = a.schema({ |
| 92 | + Todo: a |
| 93 | + .model({ |
| 94 | + content: a.string(), |
| 95 | ++ done: a.boolean(), |
| 96 | ++ priority: a.enum(['low', 'medium', 'high']) |
| 97 | + }) |
| 98 | + .authorization([a.allow.owner(), a.allow.public().to(['read'])]), |
| 99 | +}); |
| 100 | + |
| 101 | +export type Schema = ClientSchema<typeof schema>; |
| 102 | + |
| 103 | +export const data = defineData({ |
| 104 | + schema, |
| 105 | + authorizationModes: { |
| 106 | + defaultAuthorizationMode: 'apiKey', |
| 107 | + // API Key is used for a.allow.public() rules |
| 108 | + apiKeyAuthorizationMode: { |
| 109 | + expiresInDays: 30, |
| 110 | + }, |
| 111 | + }, |
| 112 | +}); |
| 113 | + |
| 114 | +// ... |
| 115 | +``` |
| 116 | + |
| 117 | +Once you save your changes to the data model, your changes will be deployed in seconds within your cloud sandbox. |
| 118 | + |
| 119 | +Our Todo data model also has authorization set up. Our model has the `authorization` method chained to it, which you can add rules to. In our example, we are allowing an owner, or the person who creates the Todo instance, to perform all actions on the data they own. We are also allowing all page viewers, including unauthenticated users, to read data. These can be modified; for example, we could remove the `.to(['read'])` and allow all visitors to perform all actions on data. We could also add permissions for signed-in users or users who belong to user groups such as `Admin`. You can learn more about all options for authorization in the [customize your auth rules](/gen2/build-a-backend/data/customize-authz/) section of the docs. |
| 120 | + |
| 121 | +Let's remove public access. |
| 122 | + |
| 123 | +```js |
| 124 | +.authorization([a.allow.owner()]), |
| 125 | +``` |
| 126 | + |
| 127 | +Then, you will see the `defineData` function, which has our schema and authorization configuration passed in as arguments. We have an `apiKey` set up to enable public access. Let's change our `defaultAuthorizationMode` to `userPool` instead so that the default is to use user authentication. |
| 128 | + |
| 129 | +```js |
| 130 | +export const data = defineData({ |
| 131 | + schema, |
| 132 | + authorizationModes: { |
| 133 | + defaultAuthorizationMode: 'userPool' |
| 134 | + } |
| 135 | +}); |
| 136 | +``` |
| 137 | + |
| 138 | +The definitions are imported and set in the `backend` file. We will not need to change anything in this file right now, but you can see its contents, which define a backend with our data and auth configurations from their respective files. |
| 139 | + |
| 140 | +```ts title="amplify/backend.ts" |
| 141 | +// amplify/backend.ts |
| 142 | +import { defineBackend } from '@aws-amplify/backend'; |
| 143 | +import { auth } from './auth/resource.js'; |
| 144 | +import { data } from './data/resource.js'; |
| 145 | + |
| 146 | +defineBackend({ |
| 147 | + auth, |
| 148 | + data |
| 149 | +}); |
| 150 | +``` |
| 151 | + |
| 152 | +### Add authentication |
| 153 | + |
| 154 | +Now let's work on our authentication configuration. Similar to the `data/resource.ts` we just worked on, the `auth/resource.ts` file has code to define our authentication configuration. In this case, setting the authentication method to log in with email. |
| 155 | + |
| 156 | +```ts title="amplify/auth/resource.ts" |
| 157 | +// amplify/auth/resource.ts |
| 158 | +import { defineAuth } from '@aws-amplify/backend'; |
| 159 | + |
| 160 | +/** |
| 161 | + * Define and configure your auth resource |
| 162 | + * When used alongside data, it is automatically configured as an auth provider for data |
| 163 | + * @see https://docs.amplify.aws/gen2/build-a-backend/auth |
| 164 | + */ |
| 165 | +export const auth = defineAuth({ |
| 166 | + loginWith: { |
| 167 | + email: true, |
| 168 | + // add social providers |
| 169 | + externalProviders: { |
| 170 | + /** |
| 171 | + * first, create your secrets using `amplify sandbox secret` |
| 172 | + * then, import `secret` from `@aws-amplify/backend` |
| 173 | + * @see https://docs.amplify.aws/gen2/deploy-and-host/sandbox-environments/features/#setting-secrets |
| 174 | + */ |
| 175 | + // loginWithAmazon: { |
| 176 | + // clientId: secret('LOGINWITHAMAZON_CLIENT_ID'), |
| 177 | + // clientSecret: secret('LOGINWITHAMAZON_CLIENT_SECRET'), |
| 178 | + // } |
| 179 | + } |
| 180 | + }, |
| 181 | + /** |
| 182 | + * enable multifactor authentication |
| 183 | + * @see https://docs.amplify.aws/gen2/build-a-backend/auth/manage-mfa |
| 184 | + */ |
| 185 | + // multifactor: { |
| 186 | + // mode: 'OPTIONAL', |
| 187 | + // sms: { |
| 188 | + // smsMessage: (code) => `Your verification code is ${code}`, |
| 189 | + // }, |
| 190 | + // }, |
| 191 | + userAttributes: { |
| 192 | + /** request additional attributes for your app's users */ |
| 193 | + // profilePicture: { |
| 194 | + // mutable: true, |
| 195 | + // required: false, |
| 196 | + // }, |
| 197 | + } |
| 198 | +}); |
| 199 | +``` |
| 200 | + |
| 201 | +Let's customize the verification email for our app. We can add a subject line by defining an object with email authentication properties. Again, we have removed comments for brevity. |
| 202 | + |
| 203 | +```diff title="amplify/auth/resource.ts" |
| 204 | +// amplify/auth/resource.ts |
| 205 | +import { defineAuth } from '@aws-amplify/backend'; |
| 206 | + |
| 207 | +export const auth = defineAuth({ |
| 208 | + loginWith: { |
| 209 | +- email: true, |
| 210 | ++ email: { |
| 211 | ++ verificationEmailSubject: 'Welcome! Verify your email!' |
| 212 | ++ }, |
| 213 | + // add social providers |
| 214 | + externalProviders: { |
| 215 | + } |
| 216 | + } |
| 217 | +}); |
| 218 | +``` |
0 commit comments