diff --git a/packages/altair-docs/docs/integrations/index.md b/packages/altair-docs/docs/integrations/index.md index e7b92092fc..a986966bef 100644 --- a/packages/altair-docs/docs/integrations/index.md +++ b/packages/altair-docs/docs/integrations/index.md @@ -1,5 +1,5 @@ --- -title: Introduction +title: Integrations has_children: true permalink: /docs/integrations order: 3 @@ -7,4 +7,97 @@ order: 3 # Integrations -There are a number of packages that have been created to help you integrate Altair within your existing application or workflow. +There are a number of packages and integration methods that have been created to help you integrate Altair within your existing application or workflow. + +## Server-Side Integrations + +### Node.js Middleware + +Integrate Altair directly into your Node.js GraphQL servers: + +#### [Express Middleware](/docs/integrations/altair-express-middleware) + + +Add Altair to your Express.js applications with minimal setup. + +#### [Koa Middleware](/docs/integrations/altair-koa-middleware) + + +Integrate Altair with Koa.js applications for GraphQL development. + +#### [Static Rendering](/docs/integrations/altair-static) + + +Render Altair as static HTML for any Node.js application or custom integration. + +## Framework Integrations + +### Modern Web Frameworks + +#### [Next.js Integration](/docs/integrations/nextjs-integration) +Complete guide for integrating Altair into Next.js applications, including App Router and Pages Router support. + +### Static Site Generators + +#### [Gatsby Plugin](/docs/integrations/gatsby-plugin-altair-graphql) + + +Official Gatsby plugin for adding Altair to your Gatsby sites during development. + +## Custom Integrations + +Using the packages above, you can create custom integrations for any platform or framework. Check out the individual integration guides for examples. + +## CDN Usage + +For quick integration without npm packages, you can use Altair directly from a CDN: + +```html + + + + + Altair + + + + + + + + + + + +
+
+
+ Altair +
+
+ + + +
+
+
+
+ + + + + +``` + +## Need Help? + +Check out our [GitHub repository](https://github.com/altair-graphql/altair) for the latest integration examples and community contributions. diff --git a/packages/altair-docs/docs/integrations/nextjs-integration.md b/packages/altair-docs/docs/integrations/nextjs-integration.md new file mode 100644 index 0000000000..526e3ca4c6 --- /dev/null +++ b/packages/altair-docs/docs/integrations/nextjs-integration.md @@ -0,0 +1,427 @@ +--- +parent: Integrations +--- + +# Next.js Integration + +Learn how to integrate Altair GraphQL Client into your Next.js applications for development and testing purposes. + +## Installation Options + +### Using altair-static + +For Next.js applications, use the `altair-static` package: + +```bash +npm install altair-static +# or +yarn add altair-static +# or +pnpm add altair-static +``` + +## Basic Integration + +### API Route Setup + +Create an API route to serve Altair in your Next.js app. You'll need to serve both the HTML and the static assets. + +#### Pages Router + +```typescript +// pages/api/altair.ts +import { renderAltair, getDistDirectory } from 'altair-static'; +import type { NextApiRequest, NextApiResponse } from 'next'; +import path from 'path'; +import fs from 'fs'; + +export default function handler(req: NextApiRequest, res: NextApiResponse) { + // Only allow in development environment + if (process.env.NODE_ENV !== 'development') { + return res.status(404).end(); + } + + const altairHtml = renderAltair({ + baseURL: '/api/altair-assets/', + endpointURL: '/api/graphql', + subscriptionsEndpoint: 'ws://localhost:3000/api/graphql', + initialQuery: `{ + # Welcome to Altair GraphQL Client for Next.js! + # Start by writing your first query here + }`, + }); + + res.setHeader('Content-Type', 'text/html'); + res.status(200).send(altairHtml); +} +``` + +```typescript +// pages/api/altair-assets/[...path].ts +import { getDistDirectory } from 'altair-static'; +import type { NextApiRequest, NextApiResponse } from 'next'; +import path from 'path'; +import fs from 'fs'; +import mime from 'mime-types'; + +export default function handler(req: NextApiRequest, res: NextApiResponse) { + if (process.env.NODE_ENV !== 'development') { + return res.status(404).end(); + } + + const { path: assetPath } = req.query; + const filePath = path.join(getDistDirectory(), ...(assetPath as string[])); + + if (!fs.existsSync(filePath)) { + return res.status(404).end(); + } + + const contentType = mime.lookup(filePath) || 'application/octet-stream'; + const fileContent = fs.readFileSync(filePath); + + res.setHeader('Content-Type', contentType); + res.status(200).send(fileContent); +} +``` + +#### App Router Version + +For Next.js 13+ with App Router: + +```typescript +// app/api/altair/route.ts +import { renderAltair } from 'altair-static'; +import { NextRequest } from 'next/server'; + +export async function GET(request: NextRequest) { + // Only allow in development + if (process.env.NODE_ENV !== 'development') { + return new Response('Not Found', { status: 404 }); + } + + const altairHtml = renderAltair({ + baseURL: '/api/altair-assets/', + endpointURL: '/api/graphql', + subscriptionsEndpoint: process.env.NODE_ENV === 'development' + ? 'ws://localhost:3000/api/graphql' + : `wss://${request.headers.get('host')}/api/graphql`, + initialQuery: `{ + # Next.js GraphQL Development Interface + # Replace this with your queries + }`, + }); + + return new Response(altairHtml, { + headers: { + 'Content-Type': 'text/html', + }, + }); +} +``` + +```typescript +// app/api/altair-assets/[...path]/route.ts +import { getDistDirectory } from 'altair-static'; +import { NextRequest } from 'next/server'; +import path from 'path'; +import fs from 'fs'; +import mime from 'mime-types'; + +export async function GET( + request: NextRequest, + { params }: { params: { path: string[] } } +) { + if (process.env.NODE_ENV !== 'development') { + return new Response('Not Found', { status: 404 }); + } + + const filePath = path.join(getDistDirectory(), ...params.path); + + if (!fs.existsSync(filePath)) { + return new Response('Not Found', { status: 404 }); + } + + const contentType = mime.lookup(filePath) || 'application/octet-stream'; + const fileContent = fs.readFileSync(filePath); + + return new Response(fileContent, { + headers: { + 'Content-Type': contentType, + }, + }); +} +``` + +## Advanced Configuration + +### Environment-Specific Setup + +```typescript +// lib/altair-config.ts +export const getAltairConfig = () => { + const baseConfig = { + initialQuery: `{ + # GraphQL Playground for ${process.env.NODE_ENV} + # Endpoint: ${process.env.NEXT_PUBLIC_GRAPHQL_URL || '/api/graphql'} + }`, + }; + + if (process.env.NODE_ENV === 'development') { + return { + ...baseConfig, + baseURL: '/api/altair-assets/', + endpointURL: '/api/graphql', + subscriptionsEndpoint: 'ws://localhost:3000/api/graphql', + }; + } + + return { + ...baseConfig, + baseURL: '/api/altair-assets/', + endpointURL: process.env.NEXT_PUBLIC_GRAPHQL_URL || '/api/graphql', + subscriptionsEndpoint: process.env.NEXT_PUBLIC_GRAPHQL_WS_URL, + }; +}; + +// pages/api/altair.ts +import { renderAltair } from 'altair-static'; +import { getAltairConfig } from '../../lib/altair-config'; + +export default function handler(req: NextApiRequest, res: NextApiResponse) { + if (process.env.NODE_ENV !== 'development') { + return res.status(404).end(); + } + + const altairHtml = renderAltair(getAltairConfig()); + + res.setHeader('Content-Type', 'text/html'); + res.status(200).send(altairHtml); +} +``` + +### Authentication Integration + +```typescript +// pages/api/altair.ts +import { renderAltair } from 'altair-static'; +import { getServerSession } from 'next-auth/next'; +import { authOptions } from './auth/[...nextauth]'; + +export default async function handler(req: NextApiRequest, res: NextApiResponse) { + if (process.env.NODE_ENV !== 'development') { + return res.status(404).end(); + } + + // Get user session for authenticated requests + const session = await getServerSession(req, res, authOptions); + + const altairHtml = renderAltair({ + baseURL: '/api/altair-assets/', + endpointURL: '/api/graphql', + initialQuery: `{ + # Authenticated GraphQL Playground + # Your session: ${session?.user?.email || 'Not logged in'} + }`, + initialHeaders: session ? { + 'Authorization': `Bearer ${session.accessToken}`, + } : {}, + }); + + res.setHeader('Content-Type', 'text/html'); + res.status(200).send(altairHtml); +} +``` + +## GraphQL Server Integration + +### With Apollo Server + +```typescript +// pages/api/graphql.ts +import { ApolloServer } from '@apollo/server'; +import { startServerAndCreateNextHandler } from '@as-integrations/next'; +import { typeDefs, resolvers } from '../../lib/schema'; + +const server = new ApolloServer({ + typeDefs, + resolvers, + // Enable introspection in development + introspection: process.env.NODE_ENV === 'development', + plugins: [ + // Add Apollo Studio plugin for production + process.env.NODE_ENV === 'production' && + require('@apollo/server/plugin/usage-reporting').default({ + sendVariableValues: { none: true }, + }), + ].filter(Boolean), +}); + +export default startServerAndCreateNextHandler(server, { + context: async (req, res) => ({ + req, + res, + // Add user context from session + user: await getUserFromRequest(req), + }), +}); +``` + +### With GraphQL Yoga + +```typescript +// pages/api/graphql.ts +import { createYoga } from 'graphql-yoga'; +import { schema } from '../../lib/schema'; + +export default createYoga({ + schema, + graphqlEndpoint: '/api/graphql', + // Enable GraphiQL only in development + graphiql: process.env.NODE_ENV === 'development', +}) + +export const config = { + api: { + bodyParser: false, + }, +} +``` + +## Development Workflow + +### Package.json Scripts + +Add convenient scripts to your `package.json`: + +```json +{ + "scripts": { + "dev": "next dev", + "dev:altair": "next dev && open http://localhost:3000/api/altair", + "graphql:introspect": "graphql-codegen --config codegen.yml", + "graphql:validate": "graphql-inspector validate schema.graphql 'src/**/*.graphql'" + } +} +``` + +### Development Page Component + +Create a dedicated development page: + +```tsx +// pages/dev/graphql.tsx (only available in development) +import { GetServerSideProps } from 'next'; +import { renderAltair } from 'altair-static'; + +interface Props { + altairHtml: string; +} + +export default function GraphQLDev({ altairHtml }: Props) { + return
; +} + +export const getServerSideProps: GetServerSideProps = async (context) => { + // Redirect in production + if (process.env.NODE_ENV !== 'development') { + return { + redirect: { + destination: '/', + permanent: false, + }, + }; + } + + const altairHtml = renderAltair({ + baseURL: '/api/altair-assets/', + endpointURL: '/api/graphql', + initialQuery: `{ + # Next.js Development GraphQL Interface + # This page is only available in development mode + }`, + }); + + return { + props: { + altairHtml, + }, + }; +}; +``` + +## TypeScript Integration + +### Generating Types from Schema + +```typescript +// lib/graphql-types.ts +import { GraphQLResolveInfo } from 'graphql'; + +export type Maybe = T | null; +export type ResolverFn = ( + parent: TParent, + args: TArgs, + context: TContext, + info: GraphQLResolveInfo +) => Promise | TResult; + +// Auto-generated types from your schema +export interface User { + id: string; + email: string; + name: string; +} + +export interface Query { + users: User[]; + user: (args: { id: string }) => User | null; +} +``` + +### Type-Safe Resolvers + +```typescript +// lib/resolvers.ts +import { Query, User } from './graphql-types'; + +export const resolvers: { Query: Query } = { + Query: { + users: async () => { + // Type-safe resolver implementation + return await getUsersFromDatabase(); + }, + user: async (_, { id }) => { + return await getUserById(id); + }, + }, +}; +``` + +## Common Issues and Solutions + +### CORS Issues +```typescript +// pages/api/graphql.ts +export default createYoga({ + schema, + cors: { + origin: process.env.NODE_ENV === 'development' + ? ['http://localhost:3000'] + : [process.env.NEXT_PUBLIC_APP_URL], + credentials: true, + }, +}) +``` + +### WebSocket Subscriptions +```typescript +// For WebSocket subscriptions in development +const altairHtml = renderAltair({ + baseURL: '/api/altair-assets/', + endpointURL: '/api/graphql', + subscriptionsEndpoint: 'ws://localhost:3000/api/graphql', + subscriptionsProtocol: 'graphql-ws', // or 'graphql-transport-ws' +}); +``` + +This integration allows you to have a powerful GraphQL development environment directly within your Next.js application, making it easy to test and develop your GraphQL APIs. \ No newline at end of file diff --git a/packages/altair-docs/docs/learn/index.md b/packages/altair-docs/docs/learn/index.md new file mode 100644 index 0000000000..44572fde91 --- /dev/null +++ b/packages/altair-docs/docs/learn/index.md @@ -0,0 +1,47 @@ +--- +title: Learn +has_children: true +permalink: /docs/learn +order: 5 +--- + +# Learn + +Whether you're new to GraphQL or looking to optimize your workflow with Altair, this section provides comprehensive guides and learning resources to help you become proficient with both GraphQL concepts and Altair's capabilities. + +## Getting Started with GraphQL + +If you're new to GraphQL, start here to understand the fundamentals: + +### [What is GraphQL?](/docs/learn/graphql) +Learn about GraphQL, how it compares to REST, and why it's becoming the preferred way to build APIs. + +## Understanding GraphQL Concepts + +### [GraphQL Subscriptions](/docs/learn/subscriptions) +Learn about real-time data with GraphQL subscriptions and how to use them effectively in Altair. + +### [GraphQL Request Extensions](/docs/learn/graphql-request-extensions) +Understand how GraphQL request extensions work and how they can enhance your API interactions. + +### [GraphQL Security](/docs/learn/graphql-security) +Best practices for securing your GraphQL APIs and common security considerations. + +## Altair-Specific Learning + +### [Web Limitations](/docs/learn/web-limitations) +Understanding the limitations when using Altair in web environments and how to work around them. + +### [Manifest V3 Changes](/docs/learn/mv3) +Learn about Chrome extension Manifest V3 changes and how they affect Altair browser extensions. + +## Need Help? + +- Check out our [Tips & Tricks](/docs/tips/) section for practical advice +- Browse the [Features](/docs/features/) documentation for detailed feature guides +- Visit our [GitHub repository](https://github.com/altair-graphql/altair) for issues and discussions +- Join our community discussions for help and support + +## Contributing to Learning Resources + +Found something missing or want to contribute to the learning materials? We welcome contributions to improve these resources. Check out our [contributing guide](/docs/contributing) to get started. \ No newline at end of file diff --git a/packages/altair-docs/docs/plugins/index.md b/packages/altair-docs/docs/plugins/index.md index 64e0347868..743cd9fc5b 100644 --- a/packages/altair-docs/docs/plugins/index.md +++ b/packages/altair-docs/docs/plugins/index.md @@ -9,12 +9,18 @@ order: 1 Altair comes with the ability to be extended via plugins. These allow you customize the functionality provided by Altair to be able to do even more than what is directly available in Altair. +## Getting Started with Plugins + +### Installing Plugins + Plugins can be added by adding them to the `plugin.list` options in the settings. Alternatively, you can discover available plugins to use from the plugin manager and add the plugin from there (which does the same thing). ![plugin manager icon](https://i.imgur.com/H0eqhvy.png) ![plugin manager](https://i.imgur.com/8zTpbTq.png) +### Plugin Format + Adding plugins to the settings uses the following format: `:@::[]->[]` @@ -27,6 +33,8 @@ Adding plugins to the settings uses the following format: **Extra options:** Depending on the plugin source specified, you can specify extra options as required. All options follow the format `[opt]->[value]`. For example, `[repo]->[imolorhe/altair]`. +### Plugin Examples + In its simplest form, you can retrieve a plugin by specifying only the plugin name, then the default version (latest) and source (npm) are used. The following are valid examples of ways to use plugins: ```yaml @@ -38,5 +46,40 @@ url:altair-graphql-plugin-some-plugin@0.0.1::[url]->[http://localhost:8002] # loads "altair-graphql-plugin-json-to-csv" plugin from github from the specified repo github:altair-graphql-plugin-json-to-csv::[repo]->[isaachvazquez/altair-graphql-plugin-json-to-csv] - ``` + +## Plugin Guides + +### [Using Plugins](/docs/plugins/using-plugins) +Comprehensive guide on how to find, install, configure, and manage plugins in Altair. + +### [Popular Plugins](/docs/plugins/popular-plugins) +Discover the most useful and popular plugins in the Altair ecosystem. + +### [Writing Your Own Plugin](/docs/plugins/writing-plugin) +Learn the basics of creating custom plugins for Altair. + +### [Submitting Your Plugin](/docs/plugins/submitting-plugin) +Guidelines for sharing your plugin with the Altair community. + +### [Plugin Policy](/docs/plugins/policy) +Rules and guidelines for plugin development and distribution. + +## For Plugin Developers + +See the [Writing a Plugin](/docs/plugins/writing-plugin) guide for information on creating custom plugins for Altair. + +## Community + +### Getting Help +- **GitHub Discussions**: Ask questions and get help from the community +- **Issues**: Report bugs or request features for existing plugins +- **Documentation**: Contribute to plugin documentation and guides + +### Contributing +- **Plugin Ideas**: Suggest new plugin concepts +- **Code Contributions**: Help improve existing plugins +- **Documentation**: Improve plugin guides and tutorials +- **Testing**: Help test plugins across different environments + +Visit our [GitHub repository](https://github.com/altair-graphql/altair) to explore the plugin ecosystem and contribute to the community! diff --git a/packages/altair-docs/docs/tips/best-practices.md b/packages/altair-docs/docs/tips/best-practices.md new file mode 100644 index 0000000000..ca3b927f4b --- /dev/null +++ b/packages/altair-docs/docs/tips/best-practices.md @@ -0,0 +1,335 @@ +--- +parent: Tips +--- + +# Best Practices + +Maximize your productivity with Altair by following these proven best practices and workflow optimizations. + +## Query Organization + +### Use Collections Effectively + +**Organize by Project or Feature**: +``` +📁 User Management + ├── Create User + ├── Update Profile + ├── Delete Account + └── 📁 Authentication + ├── Login + ├── Refresh Token + └── Logout + +📁 E-commerce + ├── 📁 Products + │ ├── List Products + │ ├── Product Details + │ └── Search Products + └── 📁 Orders + ├── Create Order + ├── Order Status + └── Order History +``` + +**Naming Conventions**: +- Use descriptive names: `Get User Profile` not `Query 1` +- Include HTTP verb: `Create Product`, `Update Inventory` +- Add context when needed: `Admin - Delete User`, `Guest - Browse Products` + +### Query Structure Best Practices + +**Use Fragments for Reusable Fields**: +```graphql +fragment UserInfo on User { + id + name + email + avatar +} + +query GetUsers { + users { + ...UserInfo + role + } +} + +query GetCurrentUser { + me { + ...UserInfo + preferences + } +} +``` + +**Meaningful Operation Names**: +```graphql +# ✅ Good - descriptive and specific +query GetUserProfileWithPreferences($userId: ID!) { + user(id: $userId) { + id + name + preferences { + theme + language + } + } +} + +# ❌ Avoid - generic and uninformative +query GetUser($id: ID!) { + user(id: $id) { + id + name + } +} +``` + +## Environment Management + +### Multi-Environment Setup + +**Recommended Environment Structure** (use snake_case for environment variables): +```json +{ + "local": { + "api_url": "http://localhost:4000/graphql", + "auth_token": "dev_token_123", + "debug": "true" + }, + "development": { + "api_url": "https://dev-api.example.com/graphql", + "auth_token": "{{dev_auth_token}}", + "debug": "true" + }, + "staging": { + "api_url": "https://staging-api.example.com/graphql", + "auth_token": "{{staging_auth_token}}", + "debug": "false" + }, + "production": { + "api_url": "https://api.example.com/graphql", + "auth_token": "{{prod_auth_token}}", + "debug": "false" + } +} +``` + +**Security Best Practices**: +- Never store production tokens directly in environment variables +- Use placeholder tokens like `{{PROD_AUTH_TOKEN}}` and fill them in locally +- Keep sensitive environments (staging, prod) in separate Altair instances +- Regularly rotate API keys and tokens + +### Variable Naming Conventions + +**Use Consistent Prefixes**: +```json +{ + "API_URL": "https://api.example.com/graphql", + "API_TIMEOUT": "30000", + "AUTH_TOKEN": "bearer_token_here", + "AUTH_REFRESH_TOKEN": "refresh_token_here", + "DB_USER_ID": "12345", + "FEATURE_FLAG_NEW_UI": "true" +} +``` + +## Authentication Strategies + +### Token Management + +**Automated Token Refresh**: +- Store tokens in environment variables +- Use Altair's environment system to manage different tokens for different stages +- Check token expiry before sending requests +- Store refresh tokens securely + +**Best practices for token storage**: +- Never commit tokens to version control +- Use environment-specific tokens +- Rotate tokens regularly +- Use short-lived access tokens with refresh tokens + +### Environment-Specific Authentication + +**Different Auth Methods per Environment**: +- Local: Simple API keys for development +- Development: JWT tokens with longer expiry +- Staging: Production-like OAuth setup +- Production: Full OAuth flow with short-lived tokens + +Configure headers in Altair's header pane per environment for secure authentication. + +## Testing and Debugging + +### Systematic Query Testing + +**Test with Incremental Complexity**: +1. **Start Simple**: Test basic field queries first +2. **Add Parameters**: Test with variables and arguments +3. **Add Nesting**: Test relationships and nested queries +4. **Add Mutations**: Test data modifications +5. **Error Scenarios**: Test with invalid data + +**Example Testing Flow**: +```graphql +# Step 1: Basic query +query { + users { + id + name + } +} + +# Step 2: Add filtering +query GetActiveUsers { + users(filter: { status: ACTIVE }) { + id + name + status + } +} + +# Step 3: Add pagination +query GetActiveUsersPage($first: Int!, $after: String) { + users(filter: { status: ACTIVE }, first: $first, after: $after) { + edges { + node { + id + name + status + } + } + pageInfo { + hasNextPage + endCursor + } + } +} + +# Step 4: Test error scenarios +query GetUserWithInvalidId { + user(id: "invalid-id") { + id + name + } +} +``` + +### Performance Testing + +**Monitor Query Performance**: +- Use response stats to track query execution time +- Set benchmarks for acceptable response times +- Test with realistic data volumes +- Monitor for N+1 query patterns + +**Query Optimization Checklist**: +- [ ] Request only necessary fields +- [ ] Use appropriate pagination limits +- [ ] Avoid deeply nested queries +- [ ] Consider query complexity scoring +- [ ] Use query batching when appropriate + +## Collaboration Workflows + +### Team Collaboration + +**Collection Sharing Strategy**: +1. **Maintain Master Collections**: Keep authoritative collections in version control +2. **Environment Separation**: Each team member maintains their own environment variables +3. **Regular Sync**: Export/import collections regularly to stay in sync +4. **Documentation**: Include query descriptions and usage notes + +**Collection Documentation Format**: +```graphql +""" +Get user profile with preferences and settings +Used by: Dashboard, Profile Page +Requirements: User must be authenticated +Test with: userId = "user_123" +Expected response time: < 200ms +""" +query GetUserProfile($userId: ID!) { + user(id: $userId) { + id + name + email + preferences { + theme + language + } + } +} +``` + +### Code Integration + +**Export for Production Code**: +- Use Altair to prototype queries +- Export working queries to your application +- Maintain consistency between Altair collections and code +- Use Altair for API regression testing + +## Maintenance and Cleanup + +### Regular Maintenance Tasks + +**Weekly**: +- [ ] Clear query history if it's getting large +- [ ] Review and clean up unused collections +- [ ] Update environment variables if needed +- [ ] Check for Altair updates + +**Monthly**: +- [ ] Export important collections as backup +- [ ] Review and update authentication tokens +- [ ] Clean up old environment configurations +- [ ] Update plugin versions if needed + +**Project Completion**: +- [ ] Archive project-specific collections +- [ ] Export final queries for documentation +- [ ] Clean up temporary test data +- [ ] Update shared team collections + +### Performance Optimization + +**Keep Altair Running Smoothly**: +- Limit query history size (Settings → General → Query history depth) +- Close unused windows +- Clear response data for large responses +- Restart Altair periodically for long sessions + +**Storage Management**: +- Export and delete old collections you no longer need +- Clear cached schema data if it becomes stale +- Monitor disk usage for desktop app data directory + +## Security Best Practices + +### Data Protection + +**Sensitive Data Handling**: +- Never commit environment files with real tokens to version control +- Use placeholder values for production credentials +- Regularly rotate API keys and tokens +- Be cautious with screenshot sharing (may contain sensitive data) + +**Access Control**: +- Use different Altair instances/profiles for different security levels +- Limit production access to necessary team members only +- Consider using temporary tokens for testing +- Log and monitor API usage where possible + +### Schema Security + +**Information Disclosure**: +- Be aware that GraphQL introspection can reveal schema structure +- Don't share schema screenshots with unauthorized parties +- Understand what information your GraphQL endpoint exposes +- Consider disabling introspection in production environments + +By following these best practices, you'll have a more organized, secure, and efficient GraphQL development workflow with Altair. Remember to adapt these practices to your team's specific needs and constraints. \ No newline at end of file diff --git a/packages/altair-docs/docs/tips/faq.md b/packages/altair-docs/docs/tips/faq.md new file mode 100644 index 0000000000..53c76d594b --- /dev/null +++ b/packages/altair-docs/docs/tips/faq.md @@ -0,0 +1,315 @@ +--- +parent: Tips +--- + +# Frequently Asked Questions (FAQ) + +Find quick answers to the most commonly asked questions about Altair GraphQL Client. + +## Getting Started + +### Q: What's the difference between the web app, desktop app, and browser extension? + +**A:** Each platform has different capabilities: + +- **Desktop App** (Recommended): Full features, best performance, no CORS limitations. [Download here](https://altairgraphql.dev/#download) +- **Browser Extension**: Convenient in-browser access, good for quick testing. Available for [Chrome](https://chrome.google.com/webstore/detail/altair-graphql-client/flnheeellpciglgpaodhkhmapeljopja) and [Firefox](https://addons.mozilla.org/en-US/firefox/addon/altair-graphql-client/) +- **Web App**: Quick access without installation, but has [limitations](/docs/learn/web-limitations) (CORS restrictions, limited file upload support). Try it at [web.altairgraphql.dev](https://web.altairgraphql.dev/) + +### Q: Which version should I use? + +**A:** For regular development work, use the **desktop app**. It provides the best experience with full features and no browser limitations. Use the browser extension for quick testing while browsing GraphQL documentation or APIs. + +### Q: How do I connect to my GraphQL API? + +**A:** +1. Set your GraphQL endpoint URL in the URL field +2. Add any required authentication headers (usually `Authorization: Bearer YOUR_TOKEN`) +3. Click "Send Request" to test the connection +4. Click "Reload Schema" to load your API's schema for auto-completion + +## Authentication & Security + +### Q: How do I authenticate with my GraphQL API? + +**A:** The most common authentication methods (see [Headers](/docs/features/headers) and [Authorization](/docs/features/auth) for more details): + +1. **Bearer Token**: Add header `Authorization` with value `Bearer YOUR_TOKEN_HERE` +2. **API Key**: Add header `X-API-Key` with your API key value +3. **Basic Auth**: Add header `Authorization` with value `Basic base64(username:password)` +4. **Custom Headers**: Add any custom authentication headers your API requires + +### Q: How do I handle token refresh automatically? + +**A:** Use [pre-request scripts](/docs/features/prerequest-scripts) to automatically fetch refreshed tokens: + +```javascript +// Pre-request script example +const refreshToken = altair.helpers.getEnvironment('refresh_token'); + +if (refreshToken) { + // Make a request to refresh the token + const response = await fetch('https://your-auth-server.com/refresh', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ refresh_token: refreshToken }) + }); + + const data = await response.json(); + + // Store the new access token + altair.helpers.setEnvironment('access_token', data.access_token); +} +``` + +Learn more about [pre-request scripts](/docs/features/prerequest-scripts) and [environment variables](/docs/features/environment-variables). + +### Q: Is it safe to store API keys in Altair? + +**A:** For development environments, yes. For production: +- Use environment variables with placeholder values +- Store actual tokens locally, not in shared collections +- Regularly rotate sensitive tokens +- Consider using temporary/limited-scope tokens for testing + +## Features & Functionality + +### Q: How do I save and organize my queries? + +**A:** Use [Collections](/docs/features/collections): +1. Write your query +2. Click "Add to collection" +3. Choose existing collection or create new one +4. Access saved queries from the sidebar +5. Organize with folders and descriptive names + +### Q: Can I use variables in my queries? + +**A:** Yes! GraphQL variables make queries dynamic. Learn more about [variables](/docs/features/variables). + +1. **In your query**: +```graphql +query GetUser($userId: ID!, $includeProfile: Boolean = false) { + user(id: $userId) { + id + name + profile @include(if: $includeProfile) { + bio + } + } +} +``` + +2. **In the Variables pane** (click Variables button or use `Ctrl/Cmd+Shift+V`): +```json +{ + "userId": "123", + "includeProfile": true +} +``` + +You can also use [environment variables](/docs/features/environment-variables) in the variables pane, though it's not recommended for complex scenarios. + +### Q: How do I work with multiple environments (dev, staging, prod)? + +**A:** Set up [environment variables](/docs/features/environment-variables): +1. Go to Settings → Environments +2. Create different environments (use snake_case naming): +```json +{ + "development": { + "api_url": "https://dev-api.example.com/graphql", + "auth_token": "dev_token_here" + }, + "production": { + "api_url": "https://api.example.com/graphql", + "auth_token": "prod_token_here" + } +} +``` +3. Use variables in queries: `{{api_url}}`, `{{auth_token}}` +4. Switch environments from the dropdown + +### Q: How do I upload files through GraphQL? + +**A:** Use the [file upload feature](/docs/features/file-upload): +1. Your API must support the [GraphQL multipart request spec](https://github.com/jaydenseric/graphql-multipart-request-spec) +2. In your mutation, use a variable for the file: +```graphql +mutation UploadFile($file: Upload!) { + uploadFile(file: $file) { + id + filename + } +} +``` +3. In Variables tab, click the file icon to select your file +4. See [File Upload documentation](/docs/features/file-upload) for details + +## Troubleshooting + +### Q: I'm getting CORS errors. How do I fix this? + +**A:** CORS errors occur when using the web app: +- **Best solution**: Use the desktop app instead +- **Alternative**: Configure your GraphQL server to allow requests from `https://web.altairgraphql.dev` +- **For development**: Temporarily disable CORS on your server (not recommended for production) + +### Q: My schema won't load. What's wrong? + +**A:** Common causes and solutions: +1. **Authentication**: Ensure you have proper auth headers set before reloading schema +2. **Introspection disabled**: Some APIs disable introspection - contact your API provider +3. **Wrong endpoint**: Verify your GraphQL endpoint URL is correct +4. **Network issues**: Check if you can access the endpoint in a browser + +### Q: Why are my queries slow? + +**A:** Query performance tips: +1. **Request only needed fields**: Don't fetch unnecessary data +2. **Use pagination**: Limit large result sets +3. **Avoid deep nesting**: Keep query depth reasonable +4. **Check server performance**: The issue might be server-side +5. **Use query analysis**: Check response stats for timing information + +### Q: I lost my queries/collections. Can I recover them? + +**A:** Recovery options: +1. **Check backups**: Look for exported collection files +2. **Application data**: Check Altair's data directory: + - Windows: `%APPDATA%\Altair GraphQL Client` + - macOS: `~/Library/Application Support/Altair GraphQL Client` + - Linux: `~/.config/Altair GraphQL Client` +3. **Cloud sync**: If enabled, data might be in your cloud account +4. **Team members**: Check if colleagues have shared collections + +## Advanced Usage + +### Q: Can I use Altair in my CI/CD pipeline? + +**A:** Not directly, but you can: +1. Export queries from Altair for use in automated tests +2. Use generated queries in your testing framework +3. Consider using Altair for manual testing and other tools for automation + +### Q: How do I write custom scripts? + +**A:** Use pre-request and post-request scripts: + +**Pre-request script** (runs before sending query): +```javascript +// Set environment variables dynamically +altair.helpers.setEnvironment('LAST_REQUEST_TIME', Date.now()); + +// Get environment variables +const apiUrl = altair.helpers.getEnvironment('API_URL'); +``` + +**Post-request script** (runs after receiving response): +```javascript +// Access response data +console.log('Response time:', altair.response.responseTime); +console.log('Status code:', altair.response.statusCode); + +// Process response +if (altair.response.body.errors) { + console.error('Query errors:', altair.response.body.errors); +} +``` + +### Q: Can I extend Altair with plugins? + +**A:** Yes! Altair supports plugins: +1. Browse available plugins in the plugin manager +2. Install plugins from npm or custom sources +3. Configure plugins in Settings → Plugins +4. See [Plugin documentation](/docs/plugins/) for more details + +### Q: How do I share queries with my team? + +**A:** Several options: +1. **Export collections**: Share collection files with team members +2. **Altair Cloud**: Use cloud sync for real-time sharing +3. **Version control**: Store exported queries in your project repository +4. **Documentation**: Copy queries to your API documentation + +## Technical Questions + +### Q: What GraphQL features does Altair support? + +**A:** Altair supports: +- Queries, Mutations, and Subscriptions +- Variables and fragments +- Introspection and schema exploration +- File uploads (multipart spec) +- Custom headers and authentication +- WebSocket subscriptions +- Real-time subscriptions (SSE, WebSocket, etc.) + +### Q: Which GraphQL servers work with Altair? + +**A:** Altair works with any GraphQL server that follows the GraphQL specification, including: +- Apollo Server +- GraphQL Yoga +- Hasura +- AWS AppSync +- Prisma +- PostGraphile +- And many others + +### Q: Can I use Altair offline? + +**A:** The desktop app works offline for: +- Writing and editing queries +- Working with saved collections +- Using previously loaded schemas + +You need internet connection for: +- Sending queries to remote APIs +- Loading/refreshing schemas +- Plugin downloads +- Cloud sync + +### Q: Does Altair collect my data? + +**A:** Altair respects your privacy: +- Local data stays on your device +- Cloud sync data is encrypted and only accessible to you +- We don't collect or analyze your queries or API data +- See our [Privacy Policy](/privacy) for full details + +## Getting Help + +### Q: Where can I get support? + +**A:** Support options: +1. **Documentation**: Check our comprehensive [docs](/docs/) +2. **GitHub Issues**: [Report bugs or request features](https://github.com/altair-graphql/altair/issues) +3. **GitHub Discussions**: [Community support and questions](https://github.com/altair-graphql/altair/discussions) +4. **Search**: Use the search function in our docs + +### Q: How do I report a bug? + +**A:** To report bugs effectively: +1. Check if the issue already exists in [GitHub Issues](https://github.com/altair-graphql/altair/issues) +2. Provide clear steps to reproduce the problem +3. Include your Altair version and platform +4. Share relevant error messages or screenshots +5. Describe expected vs actual behavior + +### Q: How can I contribute to Altair? + +**A:** Ways to contribute: +1. **Report bugs**: Help us identify and fix issues +2. **Suggest features**: Share ideas for improvements +3. **Documentation**: Help improve guides and tutorials +4. **Code contributions**: Submit pull requests +5. **Community support**: Help other users in discussions + +See our [Contributing Guide](/docs/contributing) for detailed information. + +--- + +**Still have questions?** + +Check our [Troubleshooting Guide](/docs/tips/troubleshooting) for detailed problem-solving steps, or visit our [GitHub Discussions](https://github.com/altair-graphql/altair/discussions) to ask the community! \ No newline at end of file diff --git a/packages/altair-docs/docs/tips/getting-started-guide.md b/packages/altair-docs/docs/tips/getting-started-guide.md new file mode 100644 index 0000000000..0a6878ee08 --- /dev/null +++ b/packages/altair-docs/docs/tips/getting-started-guide.md @@ -0,0 +1,177 @@ +--- +parent: Tips +--- + +# Getting Started Guide + +New to Altair? This step-by-step guide will help you get up and running quickly and effectively. + +## Step 1: Installation + +Choose the installation method that works best for your setup: + +### Desktop App (Recommended) +- **Windows/Mac/Linux**: Download from [altairgraphql.dev](https://altairgraphql.dev/#download) +- **macOS with Homebrew**: `brew install --cask altair-graphql-client` +- **Linux with Snap**: `snap install altair` + +### Browser Extensions +- **Chrome**: Install from [Chrome Web Store](https://chrome.google.com/webstore/detail/altair-graphql-client/flnheeellpciglgpaodhkhmapeljopja) +- **Firefox**: Install from [Firefox Add-ons](https://addons.mozilla.org/en-US/firefox/addon/altair-graphql-client/) + +### Web App (Limited Use) +- Access at [web.altairgraphql.dev](https://web.altairgraphql.dev/) for quick testing +- ⚠️ **Note**: Web app has limitations - use desktop/extension for full features + +## Step 2: Your First Query + +Let's connect to a GraphQL API and run your first query: + +### Using a Public API +We'll use the GitHub GraphQL API as an example: + +1. **Set the endpoint**: `https://api.github.com/graphql` +2. **Add authorization header**: + - Click the headers tab + - Add header: `Authorization` + - Value: `Bearer YOUR_GITHUB_TOKEN` + - [Get a GitHub token here](https://github.com/settings/tokens) + +3. **Write your first query**: +```graphql +query { + viewer { + login + name + bio + company + } +} +``` + +4. **Send the query**: Click the "Send Request" button (▶️) + +### Using a Local Development Server +If you have a local GraphQL server: + +1. **Set the endpoint**: `http://localhost:4000/graphql` (adjust port as needed) +2. **Write a query** based on your schema +3. **Send the request** + +## Step 3: Explore the Schema + +One of Altair's most powerful features is schema exploration: + +1. **Load the schema**: Click the reload docs button in the action bar (or use `Ctrl+Shift+R`) +2. **Browse documentation**: Click the docs button to toggle the documentation pane (or use `Ctrl+Shift+D`) +3. **Use autocomplete**: Start typing in the query editor - Altair will suggest fields and arguments + +## Step 4: Essential Features to Try + +### Environment Variables +Set up different environments (dev, staging, prod): + +1. Go to **Settings** → **Environment variables** +2. Create environments like: + ```json + { + "dev": { + "API_URL": "http://localhost:4000/graphql", + "AUTH_TOKEN": "dev_token_here" + }, + "prod": { + "API_URL": "https://api.example.com/graphql", + "AUTH_TOKEN": "prod_token_here" + } + } + ``` +3. Use variables in your endpoint: `{{API_URL}}` +4. Use in headers: `Authorization: Bearer {{AUTH_TOKEN}}` + +### Query Variables +For dynamic queries: + +1. **In the query**: +```graphql +query GetUser($userId: ID!) { + user(id: $userId) { + name + email + } +} +``` + +2. **In the Variables panel**: +```json +{ + "userId": "123" +} +``` + +### Collections +Save frequently used queries: + +1. Write your query +2. Click "Add to collection" +3. Choose or create a collection +4. Access saved queries from the sidebar + +## Step 5: Advanced Tips + +### Pre-request Scripts +Automate authentication or data preparation: + +```javascript +// Set dynamic headers +altair.helpers.setHeader('X-Request-ID', Date.now().toString()); + +// Set variables based on conditions +if (altair.data.environment.name === 'prod') { + altair.helpers.setEnvironment('timeout', 30000); +} +``` + +### Custom Themes +Personalize your workspace: + +1. Go to **Settings** → **Theme** +2. Choose from built-in themes or create custom CSS +3. Adjust syntax highlighting, font size, and colors + +### Keyboard Shortcuts +Speed up your workflow: + +- `Ctrl/Cmd + Enter`: Send request +- `Ctrl + Shift + P`: Prettify query +- `Ctrl/Cmd + /`: Toggle comments +- `Ctrl + D`: Jump to docs +- `Ctrl + Shift + V`: Toggle variables +- `Ctrl + Shift + H`: Toggle headers + +## Common First-Time Issues + +### CORS Errors +If using the web app with local APIs: +- Use the desktop app instead +- Or configure your server to allow CORS from `https://web.altairgraphql.dev` + +### Authentication Issues +- Double-check token format (often needs `Bearer ` prefix) +- Ensure token has required permissions +- Check if token is expired + +### Schema Not Loading +- Verify endpoint URL is correct +- Check if introspection is enabled on the server +- Ensure proper authentication headers are set + +## Next Steps + +Now that you're set up: + +1. **Explore [Features](/docs/features/)**: Learn about advanced capabilities +2. **Check [Tips](/docs/tips/)**: Discover workflow improvements +3. **Try [Plugins](/docs/plugins/)**: Extend functionality +4. **Join the Community**: [GitHub Discussions](https://github.com/altair-graphql/altair/discussions) + +Happy GraphQL querying! 🚀 \ No newline at end of file diff --git a/packages/altair-docs/docs/tips/migration-guide.md b/packages/altair-docs/docs/tips/migration-guide.md new file mode 100644 index 0000000000..839a19e92e --- /dev/null +++ b/packages/altair-docs/docs/tips/migration-guide.md @@ -0,0 +1,571 @@ +--- +parent: Tips +--- + +# Migration and Upgrade Guide + +This guide helps you migrate between different versions of Altair and handle breaking changes in your GraphQL workflows. + +## Altair Version Migrations + +### Major Version Upgrades + +**Pre-Upgrade Checklist**: +- [ ] Export all collections and queries +- [ ] Document current environment variables +- [ ] Note any custom plugins in use +- [ ] Backup application settings +- [ ] Take screenshots of important configurations + +### Backing Up Your Data + +**1. Export Collections** + +Before any major upgrade: + +1. Open each collection +2. Click "Export Collection" +3. Save to a safe location +4. Alternatively, export all application data: + - Settings → Import/Export → Export Application Data + +**2. Environment Variables Backup** + +```json +// Save this to a file: altair-environments-backup.json +{ + "environments": { + "local": { + "API_URL": "http://localhost:4000/graphql", + "AUTH_TOKEN": "your_token_here" + }, + "production": { + "API_URL": "https://api.example.com/graphql", + "AUTH_TOKEN": "{{PROD_TOKEN}}" + } + }, + "backup_date": "2024-01-15", + "altair_version": "5.2.1" +} +``` + +**3. Plugin Configuration Backup** + +Document your plugins: + +```json +{ + "plugins": [ + "altair-graphql-plugin-graphql-explorer", + "altair-graphql-plugin-birdseye@1.0.0", + "url:altair-graphql-plugin-custom@1.0.0::[url]->[http://localhost:8080]" + ], + "backup_date": "2024-01-15" +} +``` + +### Post-Upgrade Verification + +**1. Verify Core Functionality** +- [ ] Can connect to GraphQL endpoints +- [ ] Schema loading works correctly +- [ ] Query execution functions properly +- [ ] Collections are accessible +- [ ] Authentication still works + +**2. Check Environment Variables** +- [ ] All environments imported correctly +- [ ] Variable interpolation works +- [ ] No missing or corrupted values + +**3. Verify Plugin Compatibility** +- [ ] All plugins load successfully +- [ ] Plugin functionality works as expected +- [ ] Update incompatible plugins + +## GraphQL Schema Migrations + +### Handling Breaking Schema Changes + +**1. Identifying Breaking Changes** + +Use Altair to detect schema changes: + +```graphql +# Query to understand schema structure +query SchemaIntrospection { + __schema { + types { + name + kind + fields { + name + type { + name + kind + } + isDeprecated + deprecationReason + } + } + } +} +``` + +**2. Common Breaking Changes and Solutions** + +**Field Removal**: +```graphql +# Before (working query) +query GetUser { + user(id: "123") { + id + name + oldField # This field was removed + } +} + +# After (updated query) +query GetUser { + user(id: "123") { + id + name + newField # Use replacement field + } +} +``` + +**Type Changes**: +```graphql +# Before: String field +query GetUser { + user(id: "123") { + id + status # Was String, now enum + } +} + +# After: Enum field +query GetUser { + user(id: "123") { + id + status # Now returns UserStatus enum + } +} +``` + +**Argument Changes**: +```graphql +# Before: Single argument +query GetUsers { + users(limit: 10) { + id + name + } +} + +# After: New argument structure +query GetUsers { + users(pagination: { limit: 10, offset: 0 }) { + id + name + } +} +``` + +### Schema Migration Workflow + +**1. Gradual Migration Process** + +Create migration queries step by step: + +```graphql +# Step 1: Test new schema availability +query TestNewSchema { + __type(name: "NewUserType") { + name + fields { + name + type { + name + } + } + } +} + +# Step 2: Create hybrid query (if possible) +query HybridQuery { + # Old way (might be deprecated) + userOld: user(id: "123") { + id + name + } + + # New way + userNew: userV2(id: "123") { + id + name + additionalField + } +} + +# Step 3: Fully migrated query +query MigratedQuery { + user(id: "123") { + id + name + additionalField + } +} +``` + +**2. Testing Migration Impact** + +Create test collection for migration validation: + +```graphql +# Collection: Schema Migration Tests + +# Test 1: Basic connectivity +query ConnectivityTest { + __schema { + queryType { + name + } + } +} + +# Test 2: Core entity queries +query CoreEntityTest { + users(first: 1) { + id + name + } + posts(first: 1) { + id + title + } +} + +# Test 3: Authentication still works +query AuthTest { + me { + id + name + } +} + +# Test 4: Critical business queries +query CriticalBusinessTest { + # Add your most important queries here + dashboard { + totalUsers + totalPosts + systemStatus + } +} +``` + +## API Version Migrations + +### Versioned GraphQL APIs + +**1. Multi-Version Testing Setup** + +Environment configuration for testing multiple API versions: + +```json +{ + "api_v1": { + "API_URL": "https://api.example.com/graphql/v1", + "AUTH_TOKEN": "{{AUTH_TOKEN}}", + "API_VERSION": "1.0" + }, + "api_v2": { + "API_URL": "https://api.example.com/graphql/v2", + "AUTH_TOKEN": "{{AUTH_TOKEN}}", + "API_VERSION": "2.0" + }, + "api_v2_beta": { + "API_URL": "https://api.example.com/graphql/v2-beta", + "AUTH_TOKEN": "{{AUTH_TOKEN}}", + "API_VERSION": "2.0-beta" + } +} +``` + +**2. Version Comparison Queries** + +Create queries to compare API versions: + +```graphql +# V1 API Query +query GetUserV1 { + user(id: "123") { + id + name + email + created_at + } +} + +# V2 API Query +query GetUserV2 { + user(id: "123") { + id + name + email + createdAt # Note: camelCase in v2 + profile { # New nested structure in v2 + bio + avatar + } + } +} +``` + +### Gradual API Migration + +**1. Parallel Testing Strategy** + +Test both versions manually: + +1. **Set up two separate environments** in Altair: + - V1_API: pointing to `https://api.example.com/graphql/v1` + - V2_API: pointing to `https://api.example.com/graphql/v2` + +2. **Run the same queries** against both versions + +3. **Compare responses** to identify differences + +4. **Document breaking changes** you discover + +5. **Create migration checklist** based on differences found + +This manual testing approach helps identify: +- Schema differences +- Response format changes +- Deprecated fields +- New required fields +- Performance differences +function convertV1QueryToV2(query) { + // Simple conversion logic - adapt for your API + return query + .replace(/created_at/g, 'createdAt') + .replace(/updated_at/g, 'updatedAt'); +} + +// Run the test +testBothVersions(); +``` + +## Platform Migrations + +### Moving Between Altair Platforms + +**1. Web App to Desktop App** + +Benefits of migration: +- Better performance +- No CORS limitations +- Full feature set +- Better file upload support + +Migration steps: +1. Export all data from web app +2. Install desktop app +3. Import data to desktop app +4. Verify all functionality + +**2. Browser Extension to Desktop App** + +Migration considerations: +- Extension has storage limitations +- Desktop app offers better performance +- Some features only available in desktop + +**3. Cross-Platform Data Sync** + +Use Altair Cloud for seamless sync: +1. Create Altair Cloud account +2. Export data from old platform +3. Import to new platform +4. Enable cloud sync for future consistency + +### Operating System Migrations + +**Moving Between OS Platforms**: + +**Data Location by OS**: +- **Windows**: `%APPDATA%\Altair GraphQL Client` +- **macOS**: `~/Library/Application Support/Altair GraphQL Client` +- **Linux**: `~/.config/Altair GraphQL Client` + +**Migration Process**: +1. Export application data on old OS +2. Install Altair on new OS +3. Import application data +4. Verify settings and collections + +## Troubleshooting Migration Issues + +### Common Migration Problems + +**1. Data Import Failures** + +```javascript +// Validation script for imported data +const validateImportedData = (data) => { + const issues = []; + + // Check collections + if (!data.collections || !Array.isArray(data.collections)) { + issues.push('Collections data missing or invalid'); + } + + // Check environments + if (!data.environments) { + issues.push('Environment variables missing'); + } + + // Check queries + data.collections?.forEach((collection, index) => { + if (!collection.queries || !Array.isArray(collection.queries)) { + issues.push(`Collection ${index} has invalid queries`); + } + }); + + return issues; +}; + +// Example usage +const importedData = JSON.parse(/* your imported data */); +const issues = validateImportedData(importedData); + +if (issues.length > 0) { + console.error('Import validation issues:', issues); +} else { + console.log('Import data validation passed'); +} +``` + +**2. Environment Variable Issues** + +```javascript +// Script to fix common environment variable problems +const fixEnvironmentVariables = (environments) => { + const fixed = {}; + + Object.keys(environments).forEach(envName => { + const env = environments[envName]; + fixed[envName] = {}; + + Object.keys(env).forEach(key => { + let value = env[key]; + + // Fix common issues + if (typeof value !== 'string') { + value = String(value); + } + + // Remove extra quotes + if (value.startsWith('"') && value.endsWith('"')) { + value = value.slice(1, -1); + } + + // Validate URLs + if (key.includes('URL') && !value.match(/^https?:\/\//)) { + console.warn(`Potentially invalid URL in ${envName}.${key}: ${value}`); + } + + fixed[envName][key] = value; + }); + }); + + return fixed; +}; +``` + +### Recovery Procedures + +**1. Partial Data Recovery** + +If migration partially fails: + +```javascript +// Manual data reconstruction script +const reconstructData = (partialData) => { + const template = { + version: 1, + collections: [], + environments: {}, + settings: {}, + headers: {} + }; + + // Merge available data + if (partialData.collections) { + template.collections = partialData.collections; + } + + if (partialData.environments) { + template.environments = partialData.environments; + } + + // Add default environments if missing + if (Object.keys(template.environments).length === 0) { + template.environments.local = { + API_URL: "http://localhost:4000/graphql", + AUTH_TOKEN: "your_token_here" + }; + } + + return template; +}; +``` + +**2. Emergency Rollback** + +If migration causes issues: + +1. **Immediate Steps**: + - Don't panic - data is usually recoverable + - Check if backup files exist + - Try importing previous export + +2. **Recovery Options**: + - Reinstall previous Altair version + - Import from backup files + - Recreate critical queries manually + - Contact support with error details + +## Migration Best Practices + +### Before Migration +- [ ] Always create complete backups +- [ ] Test migration in non-production environment first +- [ ] Document current configuration +- [ ] Plan rollback strategy +- [ ] Schedule migration during low-usage periods + +### During Migration +- [ ] Follow migration steps carefully +- [ ] Verify each step before proceeding +- [ ] Keep detailed logs of any issues +- [ ] Don't skip validation steps +- [ ] Test critical functionality immediately + +### After Migration +- [ ] Verify all data imported correctly +- [ ] Test all major workflows +- [ ] Update team documentation +- [ ] Communicate changes to team members +- [ ] Monitor for any issues over first few days + +### Long-term Maintenance +- [ ] Set up regular backup schedules +- [ ] Keep migration documentation updated +- [ ] Train team members on migration procedures +- [ ] Review and update migration strategies periodically + +By following this migration guide, you can confidently upgrade Altair versions, migrate between platforms, and handle GraphQL schema changes without losing valuable work or disrupting your development workflow. \ No newline at end of file diff --git a/packages/altair-docs/docs/tips/troubleshooting.md b/packages/altair-docs/docs/tips/troubleshooting.md new file mode 100644 index 0000000000..291bf41e99 --- /dev/null +++ b/packages/altair-docs/docs/tips/troubleshooting.md @@ -0,0 +1,343 @@ +--- +parent: Tips +--- + +# Troubleshooting Guide + +Having issues with Altair? This comprehensive troubleshooting guide covers the most common problems and their solutions. + +## Connection Issues + +### "Network Error" or "Failed to fetch" + +**Symptoms**: Requests fail with network-related error messages + +**Common Causes & Solutions**: + +1. **CORS Issues (Web App)** + - **Problem**: Browser blocks requests due to CORS policy + - **Solution**: Use desktop app or browser extension instead of web app + - **Alternative**: Configure your GraphQL server to allow requests from `https://web.altairgraphql.dev` + +2. **Incorrect Endpoint URL** + - **Problem**: Wrong URL format or typo + - **Check**: Ensure URL includes protocol (`http://` or `https://`) + - **Example**: `https://api.example.com/graphql` not `api.example.com/graphql` + +3. **Server Not Running** + - **Problem**: Local development server is down + - **Check**: Verify your GraphQL server is running on the specified port + - **Test**: Try accessing the endpoint in a browser + +4. **SSL/TLS Issues** + - **Problem**: Certificate errors with HTTPS endpoints + - **Desktop App**: For development, you may need to configure your system to trust self-signed certificates + - **Note**: Only bypass certificate validation for development environments, never in production + +### "Unauthorized" or 401 Errors + +**Authentication problems are common. Here's how to fix them**: + +1. **Missing Authorization Header** + ``` + Header: Authorization + Value: Bearer your_token_here + ``` + +2. **Incorrect Token Format** + - Some APIs expect `Bearer ` prefix + - Others expect just the token + - Check your API documentation + +3. **Expired Tokens** + - **JWT Tokens**: Check expiration time + - **API Keys**: Verify they haven't been revoked + - **OAuth**: May need to refresh the token + +4. **Wrong Token Permissions** + - Ensure your token has the required scopes + - Check if the token allows GraphQL introspection + +## Schema Loading Issues + +### Schema Won't Load or Shows Empty + +**Troubleshooting Steps**: + +1. **Check Introspection** + - Some GraphQL servers disable introspection in production + - **Test Query**: + ```graphql + query { + __schema { + types { + name + } + } + } + ``` + +2. **Authentication Required for Schema** + - Set up authentication headers before reloading schema + - Some APIs require auth even for introspection + +3. **Server Configuration** + - Verify GraphQL server supports introspection + - Check if schema endpoint is different from query endpoint + +### "GraphQL Schema Error" + +**Common Solutions**: + +1. **Invalid Schema Definition** + - Server may have schema validation errors + - Check server logs for schema compilation issues + +2. **Network Timeouts** + - Large schemas may timeout during introspection + - Consider breaking down large schemas or optimizing server-side introspection + - Check server logs for performance issues + +## Query Execution Issues + +### Query Syntax Errors + +**Red underlines in the editor indicate syntax issues**: + +1. **Missing Fields in Selection Sets** + ```graphql + # ❌ Wrong - no fields selected + query { + user + } + + # ✅ Correct + query { + user { + id + name + } + } + ``` + +2. **Incorrect Variable Usage** + ```graphql + # ❌ Wrong - variable not declared + query { + user(id: $userId) { + name + } + } + + # ✅ Correct + query GetUser($userId: ID!) { + user(id: $userId) { + name + } + } + ``` + +### Variables Not Working + +**Check these common issues**: + +1. **JSON Syntax Errors** + - Variables must be valid JSON + - Use double quotes for strings + - No trailing commas + +2. **Variable Type Mismatch** + ```graphql + # Query expects String + query GetUser($name: String!) { + user(name: $name) { id } + } + ``` + ```json + // Variables should match type + { + "name": "John" // ✅ String + } + ``` + +3. **Required Variables Missing** + - Variables marked with `!` are required + - Ensure all required variables are provided + +## Performance Issues + +### Slow Query Responses + +**Optimization Strategies**: + +1. **Query Complexity** + - Avoid deeply nested queries + - Limit the number of fields requested + - Use pagination for large datasets + +2. **Network Optimization** + - Use query variables instead of hardcoded values + - Enable compression if supported by server + - Consider using query batching + +3. **Server-Side Issues** + - Check server performance monitoring + - Look for N+1 query problems + - Verify database query optimization + +### Altair Becoming Unresponsive + +**When the app freezes or becomes slow**: + +1. **Large Response Data** + - Limit response size with pagination + - Clear response history: Settings → General → Clear stored data + +2. **Memory Issues** + - Restart Altair + - Close unnecessary windows + - Clear browser cache (browser extensions) + +## Platform-Specific Issues + +### Desktop App Issues + +**App Won't Start**: +- Check if antivirus is blocking the application +- Try running as administrator (Windows) +- Clear application data and restart + +**Auto-Update Failures**: +- Download latest version manually from website +- Check internet connection +- Verify disk space available + +### Browser Extension Issues + +**Extension Not Working**: +1. **Check Extension Permissions** + - Ensure extension has access to the required sites + - Check if corporate firewall is blocking + +2. **Browser Compatibility** + - Update browser to latest version + - Disable conflicting extensions + - Try incognito/private mode + +**Content Security Policy (CSP) Errors**: +- Some websites block the extension +- Use desktop app for better compatibility +- See [CSP documentation](/docs/features/csp) for details + +### Web App Limitations + +**Missing Features**: +- File uploads not supported +- Limited local storage +- CORS restrictions +- Use desktop app for full functionality + +## Data and Settings Issues + +### Lost Queries or Settings + +**Recovery Steps**: + +1. **Check Local Storage** (Desktop App) + - Windows: `%APPDATA%/Altair GraphQL Client` + - macOS: `~/Library/Application Support/Altair GraphQL Client` + - Linux: `~/.config/Altair GraphQL Client` + +2. **Export Data Regularly** + - Settings → Import/Export → Export Application Data + - Save collections frequently + +3. **Cloud Sync Issues** + - Check internet connection + - Verify account authentication + - Try manual sync in settings + +### Settings Not Persisting + +**Common Causes**: +- Browser privacy mode (extensions) +- Insufficient storage permissions +- Corrupted settings file + +**Solutions**: +- Reset settings to defaults +- Clear application data and reconfigure +- Check browser storage permissions + +## Plugin Issues + +### Plugin Won't Load + +**Troubleshooting Steps**: + +1. **Check Plugin Format** + ``` + # Correct format + altair-graphql-plugin-plugin-name + + # With version + altair-graphql-plugin-plugin-name@1.0.0 + ``` + +2. **Verify Plugin Source** + - Ensure plugin exists in npm registry + - Check plugin compatibility with Altair version + +3. **Clear Plugin Cache** + - Remove plugin from settings + - Restart Altair + - Re-add plugin + +### Plugin Errors + +**Check Console for Errors**: +1. Open Developer Tools (F12) +2. Check Console tab for JavaScript errors +3. Look for plugin-specific error messages + +## Getting Help + +If you're still experiencing issues: + +### Before Asking for Help + +1. **Check Error Messages**: Copy exact error text +2. **Note Your Setup**: OS, Altair version, GraphQL server details +3. **Try Minimal Example**: Test with a simple query +4. **Check Recent Changes**: What changed before the issue started? + +### Where to Get Support + +1. **GitHub Issues**: [Report bugs and request features](https://github.com/altair-graphql/altair/issues) +2. **GitHub Discussions**: [Community support and questions](https://github.com/altair-graphql/altair/discussions) +3. **Documentation**: Check [all documentation sections](/docs/) + +### Information to Include + +When reporting issues, please provide: +- Altair version and platform +- GraphQL server type and version +- Exact error messages +- Steps to reproduce the issue +- Sample query that causes the problem (if applicable) + +### Emergency Workarounds + +**If Altair is completely broken**: +1. **Use Alternative GraphQL Clients** temporarily +2. **Use curl for simple requests**: + ```bash + curl -X POST \ + -H "Content-Type: application/json" \ + -H "Authorization: Bearer YOUR_TOKEN" \ + -d '{"query":"{ viewer { login } }"}' \ + https://api.github.com/graphql + ``` +3. **Reinstall Altair** as a last resort + +Remember: Most issues have simple solutions. Start with the basics (connection, authentication, syntax) before diving into complex debugging! \ No newline at end of file